Java Reference
In-Depth Information
Let us use an example to show the differences between overriding and overloading. In (a)
below, the method p(double i) in class A overrides the same method defined in class B . In
(b), however, the class A has two overloaded methods: p(double i) and p(int i) . The
method p(double i) is inherited from B .
public class Test {
public static void main(String[] args) {
A a = new A();
a.p( 10 );
a.p( 10.0 );
public class Test {
public static void main(String[] args) {
A a = new A();
a.p( 10 );
a.p( 10.0 );
}
}
}
}
class B {
public void p( double i) {
System.out.println(i * 2 );
class B {
public void p( double i) {
System.out.println(i * 2 );
}
}
}
}
class A extends B {
// This method
class A extends B {
// This method
overrides
overloads
the method in B
the method in B
double i
int i
public void p( ) {
System.out.println(i);
public void p( ) {
System.out.println(i);
}
}
}
}
(a)
(b)
When you run the Test class in (a), both a.p(10) and a.p(10.0) invoke the p(double
i) method defined in class A to display 10.0 . When you run the Test class in (b), a.p(10)
invokes the p(int i) method defined in class A to display 10 , and a.p(10.0) invokes the
p(double i) method defined in class B to display 20.0 .
Note the following:
Overridden methods are in different classes related by inheritance; overloaded meth-
ods can be either in the same class or different classes related by inheritance.
Overridden methods have the same signature and return type; overloaded methods
have the same name but a different parameter list.
To avoid mistakes, you can use a special Java syntax, called override annotation , to place
@Override before the method in the subclass. For example:
override annotation
1 public class CircleFromSimpleGeometricObject
2
extends SimpleGeometricObject {
3
// Other methods are omitted
4
5
6
@Override
public String toString() {
toString in superclass
7
return super .toString() + "\nradius is " + radius;
8 }
9 }
This annotation denotes that the annotated method is required to override a method in the
superclass. If a method with this annotation does not override its superclass's method, the
compiler will report an error. For example, if toString is mistyped as tostring , a compile
error is reported. If the override annotation isn't used, the compile won't report an error.
Using annotation avoids mistakes.
Search WWH ::




Custom Search