Java Reference
In-Depth Information
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
@Override
6
public
String toString() {
7
return super
.toString() +
"\nradius is "
+ radius;
toString
in superclass
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.
11.11
✓
✓
Identify the problems in the following code:
Check
Point
1
public class
Circle {
2
private double
radius;
3
4
public
Circle(
double
radius) {
5 radius = radius;
6 }
7
8
public double
getRadius() {
9
return
radius;
10 }
11
12
public double
getArea() {
13
return
radius * radius * Math.PI;
14 }
15 }
16
17
class
B
extends
Circle {
18
private double
length;
19
20 B(
double
radius,
double
length) {
21 Circle(radius);
22 length = length;
23 }
24
25 @Override
Search WWH ::
Custom Search