OVERRIDING

When you extend a class to produce a new one, you inherit and have access to all the non-private methods of the original class. When you want to redefine the behavior of one of these methods to suit your new class, you override the method to define a new one.
An overriding method replaces the method it overrides. Each method in a parent class can be overridden at most once in any subclass. Overriding methods should have argument lists of identical type and order. The return type of an overriding method must be identical to that of the method it overrides.
Some other special rules apply to overriding methods:
• The accessibility must not be more restricted than the original method
• The method must not throw checked exceptions of classes that are not possible for the original method.
Example #1:
class Animal {
void saySomething() {
System.out.println("Our kind is unable to speak");
}
}
class Dog extends Animal {
void saySomething() {
System.out.println("Wof!");
}
}
Animal a[] = new Animal[2];
a[0] = new Animal();
a[1] = new Dog();
a[0].saySomething();
a[1].saySomething();
Result:
Our kind is unable to speak
Wof!
Invoking Overridden Methods
It is very useful to be able to invoke an overridden method from the method that overrides it. The keyword “super” allows to access features of a class "up" in the hierarchy.
Example:
class Animal {
void saySomething() {
System.out.println("Our kind is unable to speak");
}
}
class Dog extends Animal {
void saySomething() {
super.saySomething();
System.out.println("Wof!");
}
}
Dog d = new Dog();
d.saySomething();
Result:
Our kind is unable to speak
Wof!

0 comments:

Post a Comment