public class Animal { public void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { public void sound() { System.out.println("Dog barks"); } public static void main(String args[]) { Dog d = new Dog(); d.sound(); } }
Output
Dog barks
A static method of a base class cannot be overridden, but a derived class can define a method with the same signature. This will hide base class static method, and you can't even call it with super keyword.
static methods inherited from a base class cannot be made non-static.
Call base class static method with super keyword will give compile time error.
class Parent { public static void show() { System.out.print("Parent"); } } class Child extends Parent { public static void show() { super.show(); System.out.print("Child"); } public static void main(String args[]) { Child c = new Child(); c.show(); } }
Output
Compile time error
Making base class static method non-static in a derived class will also give compile time error.
class Parent { public static void show() { System.out.print("Parent"); } } class Child extends Parent { public void show() { System.out.print("Child"); } public static void main(String args[]) { Child c = new Child(); c.show(); } }
Output
Compile time error
Method Overriding | Method Overloading |
---|---|
In method overriding, the signature of overriding method must be same as that of overridden method. In other words, the number of arguments, their types, and the order must be same in both overriding and overridden methods. | In method overloading, we have more than one functions with the same name but with different sets of argument types or the same set of argument types in different order. |
The return type of both overriding and overridden method must be same. | The return type of overloaded functions may be same or different. |
It is an example of run-time polymorphism. | It is an example of compile-time polymorphism. |
You cannot make overriding method less public than the overridden method. | Overloaded functions can have different access modifiers. |