Java笔记----子类中是否一定访问父类自定义有参构造方法?

it2023-01-08  52

public class MySQLiteOpenHelper extends SQLiteOpenHelper { private static final String DABASENAME = "liujin1015.db"; private static final int VERSION = 1; private static final String TABLENAME = "student"; Context context; //必须添加自定义的构造方法 public MySQLiteOpenHelper(Context context) { super(context, DABASENAME, null, VERSION); } public abstract class SQLiteOpenHelper implements AutoCloseable { private static final String TAG = SQLiteOpenHelper.class.getSimpleName(); private final Context mContext; @UnsupportedAppUsage private final String mName; private final int mNewVersion; private final int mMinimumSupportedVersion; private SQLiteDatabase mDatabase; private boolean mIsInitializing; private SQLiteDatabase.OpenParams.Builder mOpenParamsBuilder; /** * Create a helper object to create, open, and/or manage a database. * This method always returns very quickly. The database is not actually * created or opened until one of {@link #getWritableDatabase} or * {@link #getReadableDatabase} is called. * * @param context to use for locating paths to the the database * @param name of the database file, or null for an in-memory database * @param factory to use for creating cursor objects, or null for the default * @param version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database; if the database is * newer, {@link #onDowngrade} will be used to downgrade the database */ public SQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable CursorFactory factory, int version) { this(context, name, factory, version, null); }

分析

父类SQLiteOpenHelper自定义构造了有参方法子类如果不重写有参构造方法就会默认super();父类的无参构造方法,但是父类没有无参构造方法所以就会编译报错

解决

子类重写有参构造方法父类加一个无参构造方法

总结

总结1:   Java规定类的构造方法只能由new调用,程序员不能直接调用,但可用super()间接调用,类的构造方法是不能继承的! 总结2:   如果子类构造方法中没有显示调用父类构造方法,那么系统自动去调用父类的默认构造方法super()。

总结3:

创建有参构造方法后,系统就不再有默认无参构造方法。如果没有任何构造方法,系统会默认有一个无参构造方法。

总结4:

在没有给类提供任何构造方法时,系统会自动提供一个无参的方法实现为空的构造方法。一旦提供了自定义构造方法,系统将不会再提供这个默认构造方法。如果要使用它,程序员必须手动添加。

最新回复(0)