I am explaining method hiding and method overriding concept through a simple example
/* Java program to show that if static method is redefined by
a derived class, then it is not overriding. */
// Superclass
class Base {
// Static method in base class which will be hidden in subclass
public static void display() {
System.out.println("Static or class method from Base");
}
// Non-static method which will be overridden in derived class
public void print() {
System.out.println("Non-static or Instance method from Base");
}
}
// Subclass
class Derived extends Base {
// This method hides display() in Base
public static void display() {
System.out.println("Static or class method from Derived");
}
// This method overrides print() in Base
public void print() {
System.out.println("Non-static or Instance method from Derived");
}
}
// Driver class
public class Test {
public static void main(String args[ ]) {
Base obj1 = new Derived();
// As per overriding rules this should call to class Derive's static
// overridden method. Since static method can not be overridden, it
// calls Base's display()
obj1.display();
// Here overriding works and Derive's print() is called
obj1.print();
}
}
Output:
Static or class method from Base
Non-static or Instance method from Derived
Since we know that we can't override static method ,but if we override the static method then it is known as method hiding not method overriding .In case of simple method it is known as method overriding .I hope i have cleared your doubt
in the above example
Since method hiding is happening in above code and in case of method hiding , you have to remember one important point that reference variable will decide that which method will be invoked
If we are doing this
Student student = new Sam();
Output will be
Student is studying
if we are doing this
Sam student = new Sam();
output will be
sam is studying
In case of method overriding the object will decide that which method will be called.