Monday, 25 April 2016

Overriding vs. Hiding


An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

Main Que. is : Can I override a static method ?
Ans. No ! You can't.

Example of Hiding
class Shaan {
  public static void method() {
    System.out.println("I am Shaan");
  }
}
class Rajesh extends Shaan {
  public static void method() {
    System.out.println("I am Rajesh");
  }
}

This compiles and runs just fine.
If you try to override a static method, the compiler doesn't actually stop you

Main que. is : Isn't it an example of a static method overriding another static method?

Ans. No ! it's an example of a static method hiding another static method.


Overriding vs. Hiding
  • When you override a method, you still get the benefits of run-time polymorphism
  • When you hide, you don't.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.