Overriding - override the
functionality of any existing method
Method overriding - Having two methods with the same signature
(name, number and the type of its parameters), return type but different implementation.
Necessary Condition
One of them would exist in
the Parent class (Base Class)
Another will be in the
derived class(Child Class).
@Override annotation is
required
It is runtime activity-
overriding uses dynamic binding
If a subclass defines a class
method with the same signature as a class method in the super class, the method
in the subclass hides the one in the super class.
Sample Program
public class Alpha {
protected void addCapability() {
System.out.println("In Cocoon - Get Stronger and Stronger to Servive in this World");
}
}
public class Beta {
public void addCapability() {
System.out.println("Become Fly - Add the capability of being Happy and Fly with real Freedom");
}
public static void main(String[] args) {
Beta b = new Beta();
b.addCapability();
}
}
protected void addCapability() {
System.out.println("In Cocoon - Get Stronger and Stronger to Servive in this World");
}
}
public class Beta {
public void addCapability() {
System.out.println("Become Fly - Add the capability of being Happy and Fly with real Freedom");
}
public static void main(String[] args) {
Beta b = new Beta();
b.addCapability();
}
}
Here we have the flexibility of hiding the base functionality by adding completely new functionality in accordance with our dynamically changing requirements
Constrains
1. Method signature must be
same including return type, number of method parameters and type of parameters and
order of parameters
2. Overriding method cannot
throw higher Exception than original or overridden method. if original
method throws IOException than overriding method cannot throw super class of
IOException, the sub class can use FileNotFoundException but not
wider exception e.g. Exception or Throwable.
3. An overriding method can
allow more visibility , but not less, access than the overridden method protected instance method in
the super class can be made public but not private, in the subclass.
No comments:
Post a Comment