Blog Archive

Java abstract method and class, What does it mean ?

I am in the process of learning Android programming and came across the SQLite database. It has SQLiteOpenHelper abstract class to manage database creation and version management. Here are a few things that I noticed ...

//Class defined as abstract

public abstract class SQLiteOpenHelper extends Object

//Methods defined as abstract

abstract void onCreate(SQLiteDatabase db)
Called when the database is created for the first time.

abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.

So what is an abstract method and class?

  • An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) and which is expected to be implemented by a subclass is called an abstract method.
  • An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.If a class includes abstract methods, the class itself must be declared abstract.

Here is how the above class was implemented in a subclass

private static final String DATABASE_CREATE =
        "create table notes (_id integer primary key autoincrement, "
        + "title text not null, body text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 2;

private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

No comments :

Post a Comment