Java Basics - Polymorphism

Java Basics - Polymorphism


What is runtime polymorphism and compile time polymorphism.

    Method overloading in java is compile time polymorphis.
    Method overriding in java is runtime polymorphishm.




What is method overloading in java.

    Method overloading - 2 or more methods having same method name but different parameters type list (method signature - name and parameter list) in certain class, then the 2 or more methods are said to be overloaded. Here the return type of the methods and the declared thrown exceptions in the methods is not considered for method overloading (i.e return types of the 2 methods can be different)

Eg :
        public class A {
              public A method1(int a) throws ArithmeticException{
                     System.out.println("Value of a is : "+ a);    
                     return new A();
              }
        
              public void method1(int a, A b) throws Exception{
                       System.out.println("Value of a is : "+ a);
              }
       }


The visibility of the methods can be either public or protected or private. In case of private it will not be visible to the objects and hence we need to call internally from another public method.


What is method overriding in java

Method overriding - 2 or more methods having the same method signature and the same return types are said to be overriding. Here the declared thrown exception is considered important.

         If the method in the super class throws a Exception of type IOException, then subclass  methods should throw exceptions related to IOException or child class of IOEception. It cannot throw exception of type Exception.

         More over regarding the access specifier if the super class method is public and subclass class method is private or protected it will throw compiler error. (In short we cannot narrow down the access specifier and we cannot expand the declared thrown exception hierarchy. In short remember one thing both are rectangles which are opposite to each other where Exception is inverted triangle and access specifier is normal triangle)

eg :
Correct one
public class B extends A{
    public void method1(int a, A b) throws NumberFormatException{
        System.out.println("Value of a is : "+ a);
    }
}



InCorrect one : access specifier is private and declared exception is Exception.

public class B extends A{
    private void method1(int a, A b) throws Exception{
        System.out.println("Value of a is : "+ a);
    }
}







Comments