Runtime Polymorphism – Override

Compile time Polymorphism – Overload

Overriding

class Dog{
    public void bark(){
        System.out.println("woof ");
    }
}
class Hound extends Dog{
    public void sniff(){
        System.out.println("sniff ");
    }

    public void bark(){
        System.out.println("bowl");
    }
}

public class OverridingTest{
    public static void main(String [] args){
        Dog dog = new Hound();
        dog.bark();
    }
}

Override Rules:

  1. applies only to inherited methods

  2. object type (NOT reference variable type) determines which overridden method will be used at runtime

  3. Overriding method can have different return type

  4. Overriding method must not have more restrictive access modifier

  5. Abstract methods must be overridden
  6. Static and final methods cannot be overridden
  7. Constructors cannot be overridden
  8. It is also known as Runtime polymorphism.

Overloading

class Dog{
    public void bark(){
        System.out.println("woof ");
    }

    //overloading method
    public void bark(int num){
        for(int i=0; i<num; i++)
            System.out.println("woof ");
    }
}

Overloadding:

  • To call an overloaded method in Java, it is must to use the type and/or number of arguments to determine which version of the overloaded method to actually call.
  • Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method. .
  • When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  • It allows the user to achieve compile time polymorphism.
  • An overloaded method can throw different exceptions.
  • It can have different access modifiers.

Can we override a private method in Java?

No, you cannot. Since the private method is only accessible and visible inside the class they are declared, it's not possible to override them in subclasses. Though, you can override them inside the inner class as they are accessible there.

Can we override the final method in Java?

No, you cannot override a final method in Java, final keyword with the method is to prevent method overriding. You use final when you don't want subclass changing the logic of your method by overriding it due to security reason. This is why String class is final in Java. This concept is also used in template design pattern where template method is made final to prevent overriding.

Can we overload or override the main method in Java?

No, since main() is a static method, you can only overload it, you cannot override it because the static method is resolved at compile time without needing object information hence we cannot override the main method in Java.

results matching ""

    No results matching ""