Have a Question?

If you have any question you can ask below or enter what you are looking for!

Difference between overriding and overloading?

Overriding

  • Whatever methods parent has by default available to the child through inheritance. If child class not satisfied with parent class implementation then the child is allowed to re-define that method based on its requirement. This process is called overriding.
  • The parent class method which is overriding is called the overridden method and the child class method which is overriding is called the overriding method.
  • In overriding method resolution always takes care by JVM based on runtime object and hence overriding is also consider as Runtime polymorphism or dynamic polymorphism or late binding.
  • Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods.
  • Rules:-
    • In overriding method name and argument, the type must be matched i.e. Method signature must be same.
    • In overriding return type must be same but this rule is applicable until 1.4 version only from 1.5 version onwards we can take co-variant return types. According to this child class method return type need not be same as parent method return type its child type also allowed.
    • Co-variant concept applicable only for object types but not for primitive types.
    • Parent class private methods not available to the child and hence overriding concept not applicable to private methods.
    • Based on our requirement we can define an exactly same private method in child class. It is valid but not overriding.
    • We can’t override a parent class final method in child classes. If we are trying to override we will get compile time error.
    • A parent class abstract method we should override in child class to provide the implementation. 
    • While overriding we can’t reduce the scope of access modifier but we can increase the scope.
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 Test {
    public static void main(String[] args) {
        Dog dog = new Hound();
        dog.bark(); //bowl
    }
}

 

Tags:  , , , , , ,

One Comment

Leave a Reply

Your email address will not be published.