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.

OOP's Concepts in Java and explanation

             In the current topic, we will discuss about the what are OOP's concepts in java and detail explanation of each concepts. This is also one of important interview question for fresher and even experienced also. Experienced candidates interviewer will ask in depth questions like types of Polymorphism, explanation of Encapsulation with examples.

OOP's Concepts are as follows,
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

  • Object
      It is an real world entity. for example pen,chair,computer,book etc. In java we can say it's specimen of class.

  • Class
         It is a template or blueprint that describes behavior or state of the object. The Class contains methods, constructors, variables, and all these inside the class declaration.

Example of class : -

public class Animal {
      String breed;
      int age;
      String color;

      void hungry() {
      }

      void sleeping() {
      }
  }

  • Inheritance

         Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.
        
        Parent class can have any number of sub classes but sub class can have only one super class or parent class. This is because Java doesn't support multiple inheritance.  The parent class and child class have IS-A relationship between them
 
Example,

public class Animal {
         public String pName;
         public String familyName;
   }
                   
   public class  extends Parent {
         public String cName;
         public int childAge;
         public void printMyName(){
               System.out.println( My name is + cName+  +familyName)
         }
   }

  Advantage of inheritance is code reusability.

  • Polymorphism
      If an entity can be represented in more than one forms, that entity is said to be polymorphism.

Polymorphism means—One name many form.

In other words, polymorphism is the ability by which, we can create functions or reference variables which behaves differently in different programmatic context.

There are two types of polymorphism in java-



Runtime Polymorhism(Dynamic polymorphism):--

         Method overriding is a perfect example of  runtime polymorphism. In this kind of polymorphism, reference of class X can hold object of class X or an object of any sub classes of class X.
For e.g. if class Y extends class X then both of the following statements are valid:


  Y obj = new Y();
      //Parent class reference can be assigned to child object
  X obj = new Y();

        Since in method overriding both the classes(base class and child class) have same method, compile doesn’t figure out which method to call at compile-time. In this case JVM(java virtual machine) decides which method to call at runtime that’s why it is known as runtime or dynamic polymorphism.

Lets see an example to understand it better.


 public class X {
        public void methodA() {    
         //Base class method
              System.out.println (" methodA of class X");
        }
   }

   public class Y extends X {
         public void methodA() {          //Derived Class method  
               System.out.println ("methodA of class Y");
         }
    }
    
    public class Z {
          public static void main (String args []) {
               X obj1 = new X(); // Reference and object X
               X obj2 = new Y(); // X reference but Y object
               obj1.methodA();
               obj2.methodA();
          }
    }
   
Output: methodA of class X
              methodA of class Y

    As you can see the methodA has different-2 forms in child and parent class thus we can say methodA here is polymorphic.




Compile time Polymorhism( or Static polymorphism):-

       Compile time polymorphism is nothing but the method overloading in java. In simple terms we can say that a class can have more than one methods with same name but with different number of arguments or different types of arguments or both. To  know more about it refer method overloading in java.

Lets see the below example to understand it better,
class X {
        void methodA(int num) {
            System.out.println ("methodA:" + num);
        }
        void methodA(int num1, int num2) {
             System.out.println ("methodA:" + num1 + "," + num2);
        }
        double methodA(double num) {
             System.out.println("methodA:" + num);
             return num;
        }
   }

   class Y {
        public static void main (String args []) {
              X Obj = new X();
              double result;
              Obj.methodA(20);
              Obj.methodA(20, 30);
              result = Obj.methodA(5.5);
              System.out.println("Answer is:" + result);
         }
    }

Output:  methodA:20
               methodA:20,30
               methodA:5.5
               Answer is:5.5

            As you can see in the above example that the class has three variance of methodA or we can say methodA is polymorphic in nature since it is having three different forms. In such scenario, compiler is able to figure out the method call at compile-time that’s the reason it is known as compile time polymorphism.


  •  Encapsulation
        Encapsulation is reflected with a well defined class having all related data and behavior in a single place and than access/restrict it using appropriate access modifiers.

       We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters. Although a lesser degree of encapsulation can be achieved by making the members public or protected. Encapsulation makes it possible to maintain code that is frequently changeable by took that in one place and not scatter everywhere.



  Encapsulation Example:-

        Below is a sample code to demonstrate Encapsulation in java, Fruit class has all related data like name, taste, color.. etc and behavior like calculateCost in a single unit.

public class Fruit {

           private String name;   

           private String price;   
  
           private String taste;   

           private Fruit(String name, String price, String taste) {

                  this.name = name;   

                  this.price = price;   

                  this.taste = taste;   
           }   

           public void calculateCost() {   
           } 

           public String getName() {   

                 return name; 
           } 

           public void setName(String name) {
                 this.name = name; 
           
           }   

           public String getPrice() {   

                 return price;   
            
           }   

           public void setPrice(String price) {   

                  this.price = price;   
                                      
           }   

           public String getTaste() {   

                 return taste;   

           }   

           public void setTaste(String taste) {   

                 this.taste = taste;   
                                      
           }   
   } 
      
Advantages Of Encapsulation:-

         Encapsulation helps the developer to make the code more flexible and maintainable by binding related data in a single unit and access/restrict that using appropriate access modifier. With well encapsulation implementation, one can change one part of the code easily without affecting the other part of the code.



Related Posts:--
1) What is abstract class and interface?difference between them
2) How many types of Polymorhism in Java? Explain in brief.
3) Interface and Abstract class Interview Questions and Answers
4) Difference between Loose Coupling and Tight Coupling in Java With Examples.
5) Exception Handling Interview questions and answers
6) String Interview Questions and Answers

Polymorphism definition is that Poly means many and morphos means forms. - See more at: http://www.w3resource.com/java-tutorial/java-object-oriented-programming.php#sthash.js0jOYD3.dpuf
Polymorphism definition is that Poly means many and morphos means forms. - See more at: http://www.w3resource.com/java-tutorial/java-object-oriented-programming.php#sthash.js0jOYD3.dpuf
Polymorphism definition is that Poly means many and morphos means forms. - See more at: http://www.w3resource.com/java-tutorial/java-object-oriented-programming.php#sthash.js0jOYD3.dpuf
Polymorphism definition is that Poly means many and morphos means forms. - See more at: http://www.w3resource.com/java-tutorial/java-object-oriented-programming.php#sthash.js0jOYD3.dpuf