简体   繁体   English

Java类-构造函数的最佳做法(android)

[英]Java classes - best practice with constructors (android)

I've built a class and would like to include a constructor which will construct the class from a cursor which will point to an SQLite DB. 我已经建立了一个类,并希望包含一个构造函数,该构造函数将从一个指向SQLite DB的游标构造该类。

I also have a database helper class which sits in the same package and has static variables which give labels to the columns in the cursor. 我也有一个数据库帮助程序类,该类位于同一包中,并且具有静态变量,这些变量为游标中的列提供标签。

Should I use these references in the the constructor of the class or is that bad practice? 我应该在类的构造函数中使用这些引用,还是不好的做法?

Thanks, m 谢谢,米

here is a simple generic example asked for in the comments... 这是评论中要求的简单通用示例...

  public class carDbHelper  extends SQLiteOpenHelper{
      public static final int ROW_ID = 0;
      public static final int ROW_TYPE = 1;

      ...// all db helper code omitted

  }


 public class Car{
            private int id; 
            private String type; 

            public Car (Cursor c){
               this.id = c.getInt(carDbHelper.ROW_ID);
               this.id = c.getString(carDbHelper.TYPE_ID);
            }

        //Other code omitted
     }

Either copying object or referencing to object is good, the problem is that you need to control the object life time well. 复制对象或引用对象都是好的,问题是您需要很好地控制对象的生存时间。

I personally prefer copying object to referencing it, since it's really hard to know when object starts to exist or destroy if there're many continuous references on the same object. 我个人更喜欢复制对象而不是引用对象,因为很难知道对象何时开始存在或销毁,如果同一对象上有很多连续引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM