Java Reference
In-Depth Information
12. public Platypus(boolean hasFur) {
13. super(hasFur);
14. eggCount = 1;
15. }
16.
17. public static void main(String [] args) {
18. Platypus p = new Platypus(false);
19. p.eat(“leaves”);
20. p.breathe();
21. p.layEggs();
22.
23. }
24.}
The code compiles fi ne. The
Platypus
class correctly overrides the
eat
method in
Mammal
and also declares a new method,
layEggs
, and a fi eld,
eggCount
. Inside
main
, the following
sequence of events occurs:
1.
A new
Platypus
is instantiated on line 18, which is valid because
Platypus
is not
abstract. The constructor on line 12 is invoked.
2.
Line 13 passes the
hasFur boolean
up to the
Mammal
constructor. Line 14 sets the
eggCount
field to 1.
3.
Invoking the
eat
method on line 19 executes the overridden
eat
method on line 8.
4.
Invoking
breathe
on line 20 executes the
breathe
method in
Mammal
.
5.
Invoking
layEggs
on line 21 invokes the
layEggs
method on line 4.
Therefore, the output is
Platypus is eating leaves
Mammal is breathing
Platypus is laying eggs
We use abstract parent classes all the time in Java to represent the common attributes
and behaviors of child objects. Now that you have seen how to declare an abstract class, we
can discuss the concept of an abstract method in Java.
Abstract Methods
An
abstract method
is an instance method of a class that does not contain a method body
and must be overridden by any nonabstract child classes. Use the
abstract
keyword to
declare a method as abstract. Instead of a method body, an abstract method simply has a
semicolon at the end of its declaration. For example, the
java.io.InputStream
declares the
following method:
public abstract int read() throws IOException;
Search WWH ::
Custom Search