Académique Documents
Professionnel Documents
Culture Documents
Lecture 4
Inheritance
• Methods allows a software developer to reuse a
sequence of statements
• Inheritance allows a software developer to reuse
classes by deriving a new class from an existing
one
• The existing class is called the parent class, or
superclass, or base class
• The derived class is called the child class or
subclass.
• As the name implies, the child inherits
characteristics of the parent
• That is, the child class inherits the methods and
data defined for the parent class
28 March 2007 Java : Lecture 3 2
Inheritance
• Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Animal
weight : int
Inheritance should
+ getWeight() : int create an is-a
relationship,
meaning the child
Bird is a more specific
version of the
parent
+ fly() : void
28 March 2007 Java : Lecture 3 3
Deriving Subclasses
• In Java, we use the reserved word extends to
establish an inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}
Book
protected int pages
All these methods can access + getPages() : int
the pages instance variable. + setPages(): void
• Example:
class C extends B {
…
public C ( … ) {
super( B’s constructor arguments );
…
}
…