Method Hiding in Java and Overridning Difference
Method Hiding in Java and Overridning Difference
A static method (class method) cannot be overridden in Java. But if a static method
defined in the parent class is redefined in a child class, the child class’s method
hides the method defined in the parent class.
This mechanism is called method hiding in Java or function hiding. The syntax to
call hidden static method in a Java program is as follows:
Syntax:
superClassName.staticMethodName
All rules of method hiding are exactly the same as overriding except one rule.
3. In method hiding, method call is always resolved by Java compiler based on the
reference type. There is no role of runtime polymorphism in method hiding in java.
4. The use of static in method declaration must be the same between superclass and
subclass.
Difference between Method Hiding and Method Overriding
There are the following differences between method hiding and method overriding
in Java. They are:
1. In method hiding, both parent and child class methods should be static whereas,
in overriding, both parent and child class methods should be non-static.
Output:
Key points:
===================
System.out.println("m1-X");
System.out.println("m1-Y");
X x = new Y();
x.m1(10);
Y y = new Y();
y.m1(20);
}
}
Output:
m1-X
Compile-time error
Explanation:
2. y.m1(20); will give a compile-time error because we cannot reduce the visibility
of the inherited method from X.
There are the following differences between method hiding and method overriding
in Java. They are:
1. In method hiding, both parent and child class methods should be static whereas,
in overriding, both parent and child class methods should be non-static.