Page 365 - CITS - Computer Software Application -TT
P. 365
COMPUTER SOFTWARE APPLICATION - CITS
class Child extends Parent {
// This would produce error
void show() {}
}
3 Static methods can not be overridden (Method Overriding vs Method Hiding)
When you define a static method with the same signature as a static method in the base class, it is known as
method hiding. The following table summarizes what happens when you define a method with the same signature
as a method in a super-class.
Superclass Instance Superclass Static Method
Method
Generates a compile-time
Subclass Instance Method Overrides
error
Generates a compile-time
Subclass Static Method Hides
error
Java program to show that if the static method is redefined by a derived class, then it is not
overriding, it is hiding.
class Parent {
// Static method in base class
// which will be hidden in subclass
static void m1()
{
System.out.println(“From parent “
+ “static m1()”);
}
// Non-static method which will
// be overridden in derived class
void m2()
{
System.out.println(
“From parent “
+ “non - static(instance) m2() “);
}
}
class Child extends Parent {
// This method hides m1() in Parent
static void m1()
{
System.out.println(“From child static m1()”);
}
// This method overrides m2() in Parent
@Override public void m2()
352
CITS : IT&ITES - Computer Software Application - Lesson 94 - 100