Tuesday, 27 May 2014

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

1 comment:

  1. Nice blog..! I really loved reading through this article. Thanks for sharing such
    a amazing post with us and keep blogging...Well written article Thank You for Sharing with Us pmp training in velachery | pmp training class in chennai | pmp training fee | project management training certification | project management training in chennai

    ReplyDelete