MATERI PENDUKUNG METHOD OVERRIDING Matakuliah : M0074/PROGRAMMING II

advertisement
Matakuliah
Tahun
Versi
: M0074/PROGRAMMING II
: 2005
: 1/0
MATERI PENDUKUNG
METHOD OVERRIDING
1
• Here is a simple example. We have two classes,
Parent and Child.
class Parent {
int aValue = 1;
int someMethod(){
return aValue;
}
}
class Child extends Parent {
int aValue;
// this aValue is part of this class
int someMethod() {
// this overrides Parent's method
aValue = super.aValue + 1;
// access Parent's aValue with super
return super.someMethod() + aValue;
}
}
2
• The someMethod() of Child overrides the someMethod()
of Parent. A method of a child class with the same name
as a method in the parent class, but that is implemented
differently and therefore has different behavior is an
overridden method.
• Can you see how the someMethod() of the Child class
would return the value of 3? The method accesses the
aValue variable of Parent using the super keyword, adds
the value of 1 to it, and assigns the resulting value of 2 to
its own aValue variable. The last line of the method calls
the someMethod() of Parent, which simply returns
Parent.aValue with a value of 1. To that, it adds the value
of Child.aValue, which was assigned the value of 2 in the
previous line. So 1 + 2 = 3.
3
Download