Showing posts with label Concrete methods. Show all posts
Showing posts with label Concrete methods. Show all posts

How to access Abstract class concrete methods in java?


Basically we can't create instance for Abstract class. In that case if we need to access the concrete methods of abstract class then we need to extend abstract class to other class and by instance of those classes we call Abstract class concrete methods.

In other way we can create anonymous class and by using those instance we can call abstract class methods. Lets see example for both the approaches below,

My Abstract class:


public abstract class MyAbstract {
 
 public abstract void add();
 
 public void test(){
  System.out.println("Inside ABSTRACT class");
 }
}


Using Instance of other class:


public class MyTestClass extends MyAbstract{
 
 @Override
 public void add() {
  System.out.println("Inside add method");
 }
 
 public static void main(String[] args) {
  
  MyTestClass obj  = new MyTestClass();
  obj.test();
  obj.add(); 
 }
}

OUTPUT:


Inside ABSTRACT class
Inside add method



Using anonymous class:



public class MyTestClass {
 
 public static void main(String[] args) {
  
  MyAbstract obj = new MyAbstract() {
   
   @Override
   public void add() {
    System.out.println("Inside add method");
    
   }
  }; 
  obj.test();
  obj.add();   
 }
}


OUTPUT:


Inside ABSTRACT class
Inside add method