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.

OOP's Concepts in Java and explanation

             In this topic, we will discuss the OOP concepts in Java and provide a detailed explanation of each concept. This is also an important interview question for both freshers and experienced candidates. Interviewers often ask experienced candidates in-depth questions, such as the types of polymorphism or an explanation of encapsulation with examples.

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

  • Object
      It is a real-world entity, for example, a pen, chair, computer, or book. In Java, we can say it is an instance of a class.

  • Class
         It is a template or blueprint that defines the behavior and state of an object. A class contains methods, constructors, and variables, all of which are declared within the class definition.

Example of class : -

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

      void hungry() {
      }

      void sleeping() {
      }
  }

  • Inheritance

        Inheritance is a feature that allows a child class to inherit properties and behaviors from its parent class. In Java, this is achieved using the extends keyword. Only the properties with the public and protected access modifiers can be accessed in the child class.

A parent class can have any number of subclasses, but a subclass can have only one superclass or parent class, since Java does not support multiple inheritance. The parent class and child class share an IS-A relationship.

 
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 form, that entity is said to be a polymorphism.

Polymorphism means "one name, many forms."

In other words, polymorphism is the ability to create functions or reference variables that behave differently in different programmatic contexts.

There are two types of polymorphism in Java:

  1. Compile-time polymorphism (Static polymorphism / Method Overloading)

  2. Runtime polymorphism (Dynamic polymorphism / Method Overriding)


Runtime Polymorhism(Dynamic polymorphism):--

          Method overriding is a perfect example of runtime polymorphism. In this type of polymorphism, a reference of class X can hold either an object of class X or an object of any subclass of X.
For example, 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();

        In method overriding, both the base class and the child class have the same method, so the compiler cannot determine which method to call at compile time. In this case, the JVM (Java Virtual Machine) decides which method to call at runtime, which is 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 in Java is achieved through method overloading. In simple terms, it means a class can have multiple methods with the same name but with different numbers of arguments, different types of arguments, or both. To learn more about this, refer to 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 demonstrated through a well-defined class that contains all related data and behavior in a single place, and then restricts or provides access to them using appropriate access modifiers.

      We can achieve complete encapsulation in Java by making the members of a class private and providing access to them only through getters and setters. A lesser degree of encapsulation can be achieved by making the members public or protected. Encapsulation helps maintain code that changes frequently by keeping the data and behavior localized in one place rather than scattered throughout the application.

Encapsulation Example:

The following code demonstrates encapsulation in Java. The Fruit class groups related data (such as name, taste, and color) and behavior (such as calculateCost) into 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 developers make code more flexible and maintainable by binding related data into a single unit and controlling access through appropriate access modifiers. With proper encapsulation, one part of the code can be changed easily without affecting other parts of the code.

Thank you for visiting the blog.

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