Tuesday, 2 August 2016

Abstract method: 

     Abstract method is a method without method body. "abstract" is the key word used to declare a abstract method. Abstract method body should be implemented in the class that extends it. Abstract method will be present in the abstract class.

Example:

public abstract class Example{

public abstract void abstractmethod(); //This is a abstract method without method body.
}
     

Abstract Class:

    Abstract class is not a complete class, its incomplete. We cannot create object for the Abstract class since its incomplete. The Abstract class can be extended by a sub class where all the abstract methods need to be implemented. Abstract class contains concrete methods, abstract method and instance variables.

 We can create object for the  sub class  which extends the Abstract class. Since the sub class is a complete class that has the implementation of the abstract methods. Subclass object can be given to the Abstract class reference.

Example:

/*
*Abstract class
*/
public abstract class Example {
static int i=10;//instance variables
public abstract void method(); //abstract method
public void add(){
   System.out.println("Concrete method");
 }
}

/*
*Sub class that extends the abstract class
*/
public class SubClass extends Example {

public void method(){
   System.out.println("This is a method implementation of the abstract method");
}

public static void main(String args[]){

   Example e = new SubClass();//subclass object can be assigned to the abstract class reference
    e.method();
   System.out.println(i);
}
}


Note : 

Concrete method - method with method body
Abstract method -  method without method body. Method body will be given for sub class implementation.
Instance variable - are the variables available for the class object.



No comments: