Best example of Abstract class in Android

deeptimancode picture deeptimancode · Dec 17, 2015 · Viewed 34.1k times · Source

I am trying to design one Abstract class and method in Android and call those methods by extending the class from my parent Activity class but I don't how to call my abstract method.

MyCode :

MainActivity.java

public class MainActivity extends MyActivity {

    @Override
    public void onTest() {

       Log.d("MyLog", "onTest");

    } }

MyActivity.java

public abstract class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

    }

public abstract void onTest(); }

So this is the above code snippet , please let me know , how to use Abstract in Android because i have never done this before.

Answer

Hiren Patel picture Hiren Patel · Dec 17, 2015

I have developed Example for Abstract Class:

Abstract class:

public abstract class BaseActivity extends Activity {

    public static final String TAG = "Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(myView());
        activityCreated();
    }

    public void printMessage(String message){
        System.out.print(message);
    }


    public abstract int myView();
    public abstract void activityCreated();

}

Non Abstract class which extends Abstract class:

public class TestActivity extends BaseActivity {

@Override
public int myView() {
     return R.layout.activity_main;
}

@Override
public void printMessage(String message) {
    super.printMessage(message);
}

@Override
public void activityCreated() {
    Log.i("TestActivity", "Created");

    printMessage("Hello Hiren !!!");
  }
}

Conclusion:

  • Abstract method of abstract class must be Override in Derived class
  • Non abstract method of abstract class always call method of Super class

Hope this will make sense sure.