Abstract class having constructor, data member, methods etc

Abstract class having constructor, data member, methods etc.
An abstract class can have data member, abstract method, method body, constructor and even main() method.
  1. //example of abstract class that have method body  
  2.  abstract class Bike{  
  3.    Bike(){System.out.println("bike is created");}  
  4.    abstract void run();  
  5.    void changeGear(){System.out.println("gear changed");}  
  6.  }  
  7.   
  8.  class Honda extends Bike{  
  9.  void run(){System.out.println("running safely..");}  
  10.  }  
  11.  class TestAbstraction2{  
  12.  public static void main(String args[]){  
  13.   Bike obj = new Honda();  
  14.   obj.run();  
  15.   obj.changeGear();  
  16.  }  
  17. }  

bike is created
       running safely..
       gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
  1. class Bike12{  
  2. abstract void run();  
  3. }  
Compile time error
Rule: If you are extending any abstract class  that have abstract method, you must either provide the implementation of the method or make this class abstract.

Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such case, the end user may not be forced to override all the methods of the interface.



Comments

Popular posts from this blog

Handling Dynamic Web Tables Using Selenium WebDriver

Verify Specific Position of an Element

Read it out for TESTNG before going for an iterview