Tuesday 27 May 2014

What is abstract class and interface? Difference between them.

This is common question for Java interviewer, Please be prepare well.

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:

  1) 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.
 2) An abstract class can have one or more abstract methods.
3) An abstract class can have both abstract and non abstract (or concrete) method.
 4) 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();
} 



Related Posts:--
1) OOP's Concepts in Java and explanation
2) How many types of Polymorhism in Java ? Explain in brief.
3) Interface and Abstract class Interview Questions and Answers
4) What is Generics in Java with examples ? and What are the advantages of using Generics.

No comments:

Post a Comment