100% found this document useful (1 vote)
156 views

Chapter Three Inheritance

This document discusses inheritance in object-oriented programming. It begins by listing the chapter objectives, which include developing subclasses through inheritance, invoking superclass constructors and methods, overriding and overloading methods, and exploring polymorphism. It then provides an introduction to the three pillars of OOP: encapsulation, inheritance, and polymorphism. The document goes on to define inheritance as allowing new classes to be defined from existing classes. It uses an example of geometric shapes to illustrate defining a superclass and subclasses that inherit and extend the superclass. It provides code examples of a GeometricObject superclass and Circle and Rectangle subclasses.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
156 views

Chapter Three Inheritance

This document discusses inheritance in object-oriented programming. It begins by listing the chapter objectives, which include developing subclasses through inheritance, invoking superclass constructors and methods, overriding and overloading methods, and exploring polymorphism. It then provides an introduction to the three pillars of OOP: encapsulation, inheritance, and polymorphism. The document goes on to define inheritance as allowing new classes to be defined from existing classes. It uses an example of geometric shapes to illustrate defining a superclass and subclasses that inherit and extend the superclass. It provides code examples of a GeometricObject superclass and Circle and Rectangle subclasses.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Chapter Three

Inheritance

1
Objectives
• To develop a subclass from a superclass through inheritance .
• To invoke the superclass’s constructors and methods using the super keyword.
• To override instance methods in the subclass .
• To distinguish differences between overriding and overloading .
• To explore the toString() method in the Object class .
• To discover polymorphism and dynamic binding .
• To describe casting and explain why explicit downcasting is necessary.
• To explore the equals() method in the Object class.
• To restrict access to data and methods to subclasses using the protected visibility
modifier .
• To prevent class extending and method overriding using the final modifier .

2
Introduction
• The three pillars of object-oriented programming
are
1. Encapsulation,
2. Inheritance, and
3. Polymorphism.

3
Inheritance

• Object-oriented programming allows you to


define new classes from existing classes. This is
called inheritance.
• Inheritance is an important and powerful feature
for reusing software.
• Suppose you will need to define classes to model
circles, rectangles, and triangles. These classes
have many common features.
• What is the best way to design these classes so as
to avoid redundancy? The answer is to use
inheritance. 4
Superclasses and Subclasses

• Inheritance enables you to define a general class (e.g., a


superclass) and later extend it to more specialized classes
(e.g., subclasses).

• Different classes may have some common


properties and behaviors, which can be generalized in a
class that can be shared by other classes.

• You can define a specialized class that extends the


generalized class.

• The specialized classes inherit the properties and methods


from the general class. 5
Superclasses and Subclasses

• In Java terminology, a class C1 extended from


another class C2 is called a subclass, and C2
is called a superclass.

• A superclass is also referred to as a parent class or a


base class, and a subclass is referred to as a child
class, an extended class, or a derived class.

• A subclass inherits accessible data fields and


methods from its superclass and may also add new
data fields and methods. 6
Superclasses and Subclasses

• The Circle class inherits all accessible data fields


and methods from the GeometricObject class.

• In addition, it has a new data field, radius, and its


associated get and set methods.

• The Circle class also contains the getArea() ,


getPerimeter() , and getDiameter() methods for
returning the area, perimeter, and diameter of the
circle.
7
Superclasses and Subclasses

• The Rectangle class inherits all accessible data


fields and methods from the GeometricObject
class.
• In addition, it has the data fields width and
height and their associated get and set methods.

• It also contains the getArea() and getPerimeter()


methods for returning the area and perimeter of
the rectangle.

8
Superclasses and Subclasses

9
Example 1: GeometricObject Superclass
Import java.util.Date;
public class GeometricObject {
private String color = "white";
private boolean filled;
private Date dateCreated;
/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new Date();
}
// Construct a geometric object with the specified color and filled value

public GeometricObject(String color, boolean filled) {


dateCreated = new Date();
this.color = color;
this.filled = filled;
}
/** Return color */
public String getColor() {
return color;
}

/** Set a new color */


public void setColor(String color) {
this.color = color;
} 10
GeometricObject Superclass
/** Return filled. */
public boolean isFilled() {
return filled;
}

/** Set a new filled */


public void setFilled(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public Date getDateCreated() {
return dateCreated;
}
/** Return a string representation of this object*/
public String toString() {
return "created on " + dateCreated + "\ncolor: " +
color + " and filled: " + filled;
}
} 11
Circle Subclass
public class Circle extends GeometricObject{
private double radius;

public Circle() {
}

public Circle(double radius) {


this.radius = radius;
}

public Circle(double radius, String color, boolean filled) {


this.radius = radius;
setColor(color);
These two methods are
setFilled(filled); inherited from the superclass.
}

/** Return radius */


public double getRadius() {
return radius;
}

/** Set a new radius */


public void setRadius(double radius) {
this.radius = radius;
} 12
Circle Subclass

/** Return area */


public double getArea() {
return radius * radius * Math.PI;
}

/** Return diameter */


public double getDiameter() {
return 2 * radius;
}

/** Return perimeter */


public double getPerimeter() {
return 2 * radius * Math.PI;
}

/** Print the circle info */


public void printCircle() {
System.out.println("The circle is created " +
getDateCreated()+ " and the radius is " + radius);
}
} 13
Circle Subclass
• The keyword extends tells the compiler that the Circle
class extends the GeometricObject class.
– Thus inheriting the methods getColor, setColor, isFilled,
setFilled, and toString.

• The overloaded constructor Circle(double radius,


String color, boolean filled) is implemented by invoking
the setColor and setFilled methods to set the color and
filled properties .

• These two public methods are defined in the base


class/superclass GeometricObject and are inherited in
Circle, so they can be used in the derived class. 14
Circle Subclass

15
Rectangle Subclass
public class Rectangle extends GeometricObject {

private double width;


private double height;

public Rectangle() {
}

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

public Rectangle( double width, double height, String color, boolean


filled) {
this.width = width;
this.height = height; These two methods are
setColor(color); inherited from the superclass.
setFilled(filled);
}

/** Return width */


public double getWidth() {
return width;
} 16
Rectangle Subclass
/** Set a new width */
public void setWidth(double width) {
this.width = width;
}
/** Return height */
public double getHeight() {
return height;
}

/** Set a new height */


public void setHeight(double height) {
this.height = height;
}

/** Return area */


public double getArea() {
return width * height;
}

/** Return perimeter */


public double getPerimeter() {
return 2 * (width + height);
}
} 17
Rectangle Subclass

• The keyword extends tells the compiler that the


Rectangle class extends the GeometricObject
class, thus inheriting the methods getColor,
setColor, isFilled, setFilled, and toString.

18
Rectangle Subclass

• The following code creates objects of Circle and


Rectangle and invokes the methods on these
objects.

• The toString() method is inherited from the


GeometricObject class and is invoked from a
Circle object and a Rectangle object.

19
TestCircleRectangle Class
public class TestCircleRectangle { inherited from
public static void main(String[] args) { superclass.

Circle circle = new Circle(1);


System.out.println("A circle " + circle.toString());
System.out.println("The color is “+ circle.getColor());
System.out.println("The radius is “+ circle.getRadius());
System.out.println("The area is "+ circle.getArea());
System.out.println("The diameter is “+
circle.getDiameter());

Rectangle rectangle = new Rectangle(2, 4);


System.out.println("\nA rectangle " +
rectangle.toString() );
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +
rectangle.getPerimeter() );
}
}
20
Example 2: Dog Class
public class Dog {
private String name;
private int fleas;

public Dog(String n, int f) {


name = n;
fleas = f;
}

public String getName() {


return name;
}

public int getFleas() {


return fleas;
}

public void speak() {


System.out.println("Woow");
}
} 21
Cat Class
public class Cat {
private String name;
private int hairballs;

public Cat(String n, int h) {


name = n;
hairballs = h;
}

public String getName() {


return name;
}

public int getHairballs() {


return hairballs;
}

public void speak() {


System.out.println("Meow");
}
} 22
Problem: Code Duplication

• Dog and Cat have the name field and the


getName method in common.

• Classes often have a lot of state and


behavior in common

• Result: lots of duplicate code!

23
Solution: Inheritance
• Inheritance allows you to write new classes that
inherit from existing classes

• The existing class whose properties are inherited


is called the "parent" or superclass

• The new class that inherits from the super class is


called the "child" or subclass

• Result: Lots of code reuse!


24
Dog Cat
String name String name
int fleas int hairballs
String getName() String getName()
int getFleas() int getHairballs()
void speak() void speak()

using
inheritance

superclass
Animal
subclass
String name
subclass String getName()

Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
void speak() void speak() 25
Animal Superclass
public class Animal {

private String name;

public Animal(String n) {
name = n;
}

public String getName() {


return name;
}
}

26
Dog Subclass
public class Dog extends Animal {

private int fleas;

public Dog(String n, int f) {


super(n); // calls Animal constructor
fleas = f;
}

public int getFleas() {


return fleas;
}

public void speak() {


return System.out.println("Woow");
}
}
27
Cat Subclass
public class Cat extends Animal {

private int hairballs;

public Cat(String n, int h) {


super(n); // calls Animal constructor
hairballs = h;
}

public int getHairballs() {


return hairballs;
}

public void speak() {


return System.out.println("Meow");
}
}
28
Using the super Keyword

• Are superclass’s Constructor Inherited? The Answer is No.


• They are not inherited. They are invoked explicitly or
implicitly. Explicitly using the super keyword.
• A constructor is used to construct an instance of a class.
• Unlike properties and methods, a superclass's constructors
are not inherited in the subclass.
• They can only be invoked from the subclasses'
constructors, using the keyword super.
• If the keyword super is not explicitly used, the superclass's
no-arg constructor is automatically invoked.

29
Using the super Keyword

• The keyword super refers to the superclass of the class in


which super appears.
• This keyword can be used in two ways:
– To call a superclass constructor.
– To call a superclass method.

• Caution:
– You must use the keyword super to call the superclass
constructor.
– Invoking a superclass constructor’s name in a subclass causes
a syntax error.
– Java requires that the statement that uses the keyword super
appear first in the constructor. 30
Using the super Keyword
1. Calling Superclass Constructors
– The syntax to call a superclass’s constructor is:
super(), or super(parameters);
– The statement super() invokes the no-arg constructor of its
superclass, and the statement super(arguments) invokes the
superclass constructor that matches the arguments.
– The statement super() or super(arguments) must appear in
the first line of the subclass’s constructor; this is the only way
to explicitly invoke a superclass constructor.
– For example:

public Circle(double radius, String color, boolean filled){


super(color, filled);
this.radius = radius;
}
31
Using the super Keyword

2. Constructor Chaining
– A constructor may invoke an overloaded constructor or its
superclass’s constructor.
– If none of them is invoked explicitly, the compiler automatically
puts super() as the first statement in the constructor. For example:

public A() { public A() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}
32
Declaring a Subclass
• A subclass extends properties and methods from
the superclass. You can also:
 Add new properties
 Add new methods
 Override the methods of the superclass

33
Calling Superclass Methods

• The keyword super can also be used to reference a method other than
the constructor in the superclass. The syntax is:
super.method(parameters);
• You could rewrite the printCircle() method in the Circle class as
follows:

public void printCircle() {


System.out.println("The circle is created " +
super.getDateCreated()+“and the radius is “ +
radius);
}

• It is not necessary to put super before getDateCreated() in this case,


however, because getDateCreated is a method in the
GeometricObject class and is inherited by the Circle class.
34
The protected Data Field and Methods

• A protected member of a class can be accessed


from a subclass
• Private members can be accessed only from
inside of the class, and public members can be
accessed from any other classes.
• The keyword protect is used to allow
subclasses to access data fields or methods
defined in the superclass, but not to allow non-
subclasses to access these data fields and
methods.
35
The protected Data Field and Methods

This table summarizes the accessibility modifiers which show to


what extent the members of a class will be accessed.

36
The protected Data Field and Methods
This Figure illustrates how a
public, protected, default, and
private data field or method in
class C1 can be accessed
from a class C2 in the same
package, from a subclass C3
in the same package, from a
subclass C4 in a different
package, and from a class C5
in a different package.

37
The protected Data Field and Methods
• Use the private modifier to hide the members of the class
completely so that they cannot be accessed directly from outside the
class.

• Use no modifiers (the default) in order to allow the members of the


class to be accessed directly from any class within the same package
but not from other packages.

• Use the protected modifier to enable the members of the class to be


accessed by the subclasses in any package or classes in the same
package.

• Use the public modifier to enable the members of the class to be


accessed by any class. 38
The protected Data Field and Methods

• The private and protected modifiers can be used


only for members of the class.

• The public modifier and the default modifier (i.e.,


no modifier) can be used on members of the class
as well as on the class.

• A class with no modifier (i.e., not a public class) is


not accessible by classes from other packages.

39
NOTE

• An instance method can be overridden only if it is


accessible. Thus a private method cannot be overridden,
because it is not accessible outside its own class. If a
method defined in a subclass is private in its superclass,
the two methods are completely unrelated.

• Like an instance method, a static method can be


inherited. However, a static method cannot be
overridden. If a static method defined in the superclass is
redefined in a subclass, the method defined in the
superclass is hidden. The hidden static methods can be
invoked using the syntax
SuperClassName.staticMethodName. 40
Overriding vs. Overloading

• Overloading means to define multiple methods


with the same name but different signatures.

• Overriding means to provide a new


implementation for a method in the subclass.

• To override a method, the method must be defined


in the subclass using the same signature and the
same return type.
41
Overriding vs. Overloading
The following program shows 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.

42
Overriding vs. Overloading

• 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.

43
Overriding vs. Overloading

• Note:
– Overridden methods are in different classes related by
inheritance; overloaded methods 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

44
Overriding vs. Overloading

• To avoid mistakes, you can use a special Java


syntax, called override annotation, to place
@Override before the method in the subclass.
• For example:

public class Circle extends GeometricObject {


// Other methods are omitted

@Override
public String toString() {
return super.toString()+"\nradius is " + radius;
}
}
45
Is-a Versus Has-a Relationships
• Is-a represents the inheritance/extends
• Has-a represents composition/aggregation
• Example: Dog is an Animal (inheritance)
Dog has an Eyes (composition)
House is a Building (inheritance)
House has a door (composition)

Person

is a is a

Student Teacher

has a has a

BirthDate 46
Object Composition

• Composition is actually a special case of the


aggregation relationship.
• Aggregation models has-a relationships and
represents an ownership relationship between two
objects.
• The owner object is called an aggregating object
and its class an aggregating class.
• The subject object is called an aggregated object
and its class an aggregated class.
• Aggregation is weak relationship but composition
is strong relationship. 47
Object Composition
• An object may be owned by several other aggregating objects. If an
object is exclusively owned by an aggregating object, the relationship
between them is referred to as composition.

• For example, “a student has a name” is a composition relationship


between the Student class and the Name class, whereas “a student has an
address” is an aggregation relationship between the Student class and
the Address class, because an address may be shared by several students.

48
Class Representation
• An aggregation relationship is usually represented as a data
field in the aggregating class.
• For example, the relationship in the following Figure can be
represented as follows:

49
Aggregation or Composition
• Since aggregation and composition relationships
are represented using classes in similar ways,
many texts don’t differentiate them and call both
compositions.
• Aggregation: “is part of”
• Composition: “is entirely made up of”
• stronger version of aggregation
• the parts live and die with the whole

50
Aggregation Between Same Class
• Aggregation may exist between objects of the same
class. For example, a person may have a supervisor.
1
Person
Supervisor
1

In the relationship “a person has a supervisor,” as shown in Figure above, a


supervisor can be represented as a data field in the Person class, as follows:

public class Person {


// The type for the data is the class itself
private Person supervisor;
...
} 51
Aggregation Between Same Class
What happens if a person can have several supervisors?
You may use an array to store supervisors a show below.

1
Person
Supervisor
m

public class Person {


...
private Person[] supervisors;
}

52
The Object Class and Its Methods
Every class in Java is descended from the java.lang.Object
class. If no inheritance is specified when a class is defined,
the superclass of the class is Object by default. For
example, the following two class definitions are the same:

public class Circle { public class Circle extends Object {


... Equivalent
...
} }

The toString method is found in the Object class. The toString()


method returns a string representation of the object.
53
End!!

54

You might also like