Overriding method is an instance method in a subclass that has the same implementations with the instance method of the super class. It means that both instance methods has the same name, parameters, and return type. Note that this overriding is in the instance method only because when it comes to static methods, it is no longer called overriding but instead hiding methods.
Hiding method is a static method in a subclass that has the same implementations with the static method of the super class. It means that both static methods has the same name, parameters, and return type.
The difference in overriding and hiding method is during the invoking of the methods. When you call an instance method, you create an object first which determines the type of the object. So, when you invoke that method, it is clear in the compiler that you wanted to call the instance method of the subclass because you are creating an object of that subclass even if the type of that variable is in the super class. Unlike in the static method where you need to specify the calling class. It means that in the static method, you are just hiding the static method of the super class. The static method of the super class is totally a different method from the subclass.
Note that in the overriding method, if you want to call the method from the super class, you need to use the super keyword.
=====================
class OverridingOrHiding extends MotherClass{
static final String childName = "Child";
@Override
void displayInstanceMethod() {
System.out.println(childName + " Instance method");
System.out.println("Used super keyword to invoke from mother class");
super.displayInstanceMethod();
}
static void displayStaticMethod(){
System.out.println(childName + " Static method");
}
public static void main(String[] args) {
System.out.println("=======instance==========");
OverridingOrHiding obj = new OverridingOrHiding();
obj.displayInstanceMethod();
System.out.println("=======static==========");
OverridingOrHiding.displayStaticMethod();
MotherClass.displayStaticMethod();
}
}
class MotherClass {
static final String name = "Mother";
void displayInstanceMethod(){
System.out.println(name + " Instance method");
}
static void displayStaticMethod(){
System.out.println(name + " Static method");
}
}=====================
Result:
=======instance==========Child Instance methodUsed super keyword to invoke from mother classMother Instance method=======static==========Child Static methodMother Static method
YOU ARE READING
Java Programming
Randomhttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...