Tuesday, 27 May 2014

Abstract class and Interface in Java

This is common question for Java interviewer fresher or even mid level experienced one.

Abstract Class

            The Abstract class can not be instantiate. We can never directly create an object of Abstract class even if it contains a Constructor and all methods are implemented. The abstract class contains both abstract and non-abstract methods(abstract means can not be implemented). Use abstract keyword to declare abstract class. 

see the below example,
        
abstract class Employee{
}
              
class Salary {
     public static void main(String[] args) {
           Employee emp=new Employee();  //it will give the compile time error.
     }
}


     The abstract class object can be created using the reference of extending class. You can extend abstract class and implement all abstract method in sub-class. For example below.

abstract class Employee{
      abstract void method1();
      public void method2(){
            //some statements
      }
}

class Salary extends Employee {
        public void method1(){
             System.out.println("method1.....");
        }
}

class MainExample{
         public static void main(String[] args){
                 Employee e=new Salary();
                 e.method1();         //it will call method1 of Salary class.
         }
}
           
Rules for Abstract Classes:
  •  A class can be marked as abstract with out containing any abstract method. But if a class has even one   abstract method, then the class has to be an abstract class.
  •  An abstract class can have one or more abstract methods.
  • An abstract class can have both abstract and non abstract (or concrete) method.
  • Any sub-class extending from an abstract class should either implement all the abstract methods of the super-class or the sub-class itself should be marked as abstract.

Interface

       Interface contains only abstract methods(not implemented). It is not a class. A class can implement interface. Use interface keyword to declare interface. and all variables inside the interface implicitly public final variables or constants,this useful to declare the constants.

      Interface doesn't contain any costructors & interface can extends multiple interfaces.

public interface InterfaceEx{
      int a=10;        //it is equivalent to public static int a=10;
      public void method1();
} 

Thank you for visiting the blog.

No comments:

Post a Comment