0% found this document useful (0 votes)
4 views

05 Inheritance Updated

Uploaded by

rahafaltamimi41
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

05 Inheritance Updated

Uploaded by

rahafaltamimi41
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 5

Object-Oriented Programming:
Inheritance – Part 1
Java™ How to Program, 10/e
Late Objects Version

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.


5.1 Introduction
🞂 Inheritance
▪ is a mechanism in which one object acquires all the
properties and behaviors of parent object. The idea
behind inheritance in java is that you can create new
classes that are built upon existing classes.
▪ Can save time during program development by basing new
classes on existing proven and debugged high-quality software.
▪ Increases the likelihood that a system will be implemented and
maintained effectively.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.1 Introduction (Cont.)
🞂 When creating a class, rather than declaring completely new
members, you can designate that the new class should
inherit the members of an existing class.
▪ Existing class is the superclass
▪ New class is the subclass
🞂 A subclass can be a superclass of future subclasses.
🞂 A subclass can add its own fields and methods.
🞂 A subclass is more specific than its superclass and
represents a more specialized group of objects.
🞂 The subclass exhibits the behaviors of its superclass and can
add behaviors that are specific to the subclass.
▪ This is why inheritance is sometimes referred to as specialization.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.1 Introduction (Cont.)
🞂 The direct superclass is the superclass from which the
subclass explicitly inherits.
🞂 An indirect superclass is any class above the direct
superclass in the class hierarchy.
🞂 The Java class hierarchy begins with class Object (in
package java.lang)
▪ Every class in Java directly or indirectly extends (or “inherits
from”) Object.
🞂 Java supports only single inheritance, in which each
class is derived from exactly one direct superclass.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.1 Introduction (Cont.)
🞂 We distinguish between the is-a relationship and the
has-a relationship
🞂 Is-a represents inheritance
▪ In an is-a relationship, an object of a subclass can also be
treated as an object of its superclass
🞂 Has-a represents composition
▪ In a has-a relationship, an object contains as members
references to other objects

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.2 Superclasses and Subclasses
🞂 Figure 9.1 lists several simple examples of superclasses
and subclasses
▪ Superclasses tend to be “more general” and subclasses “more
specific.”
🞂 Because every subclass object is an object of its
superclass, and one superclass can have many
subclasses, the set of objects represented by a
superclass is typically larger than the set of objects
represented by any of its subclasses.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.2 Superclasses and Subclasses
(Cont.)
🞂 A superclass exists in a hierarchical relationship with its
subclasses.
🞂 Fig. 9.2 shows a sample university community class hierarchy
▪ Also called an inheritance hierarchy.
🞂 Each arrow in the hierarchy represents an is-a relationship.
🞂 Follow the arrows upward in the class hierarchy
▪ an Employee is a CommunityMember”
▪ “a Teacher is a Faculty member.”
🞂 CommunityMember is the direct superclass of Employee,
Student and Alumnus and is an indirect superclass of all the other
classes in the diagram.
🞂 Starting from the bottom, you can follow the arrows and apply
the is-a relationship up to the topmost superclass.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.2 Superclasses and Subclasses
(Cont.)
🞂 Fig. 9.3 shows a Shape inheritance hierarchy.
🞂 Van follow the arrows from the bottom of the diagram
to the topmost superclass in this class hierarchy to
identify several is-a relationships.
▪ A Triangle is a TwoDimensionalShape and is a Shape
▪ ASphere is a ThreeDimensionalShape and is a Shape.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.2 Superclasses and Subclasses
(Cont.)
🞂 Not every class relationship is an inheritance
relationship.
🞂 Has-a relationship
▪ Create classes by composition of existing classes.
▪ Example: Given the classes Employee, BirthDate and
TelephoneNumber, it’s improper to say that an Employee is a
BirthDate or that an Employee is a TelephoneNumber.
▪ However, an Employee has a BirthDate, and an Employee has
a TelephoneNumber.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.3 Example without inheritance
public class CheckingAccount {
private String type;
private String name;
private long number;
private double balance;
private boolean overdrawn;
public CheckingAccount(String name, long number, double amount) {
type = “Checking account”;
this.name = name;
this.number = number;
balance = amount;
overdrawn = false; We assume that all
} required setters and
public void deposit(double amount) { getters are defined

balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
} © Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.3 Example without inheritance
(Cont.)
public class SavingAccount {
private String type;
private String name;
private long number;
private double balance;
private double interestRate = 0.10;
public SavingAccount(String name, long number, double amount) {
type = “Saving account”;
this.name = name;
this.number = number;
balance = amount;
} We assume that all
required setters and
public void deposit(double amount) {
getters are defined
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
}

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.3 Example without inheritance
(Cont.)
public class TestAccount {
public static void main (String[] args){
SavingAccount sa= new SavingAccount("Saleh", 1111, 10000.0);
System.out.println( "account type: " + sa.getType());
System.out.println( "account name: " + sa.getName() );
System.out.println( "initial amount: " + sa.getBalance() );
sa.deposit(5000);
System.out.println( "new amount after deposit: "+sa.getBalance());

CheckingAccount ca= new CheckingAccount("Ahmad", 2222, 20000.0);


System.out.println( "account type: " + ca.getType());
System.out.println( “account name: “ + ca.getName() );
System.out.println( “initial amount:“ + ca.getBalance() );
ca.deposit(6000);
System.out.println(“new amount after deposit: “+ca.getBalance());
ca.withdraw(3000);
System.out.println(“new amount after withdrawal: “ + ca.getBalance());
}
}
© Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.3 Example output

account type: Saving account


account name: Saleh
initial amount: 10000.0
new amount after deposit: 15000.0
account type: Checking account
account name: Ahmad
initial amount: 20000.0
new amount after deposit: 26000.0
new amount after withdrawal: 23000.0

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.4 Example with inheritance
public class Account {
private String type;
private String name;
private long number;
private double balance;
public Account(String type, String name, long number, double amount){
this.type = type;
this.name = name;
this.number = number;
balance = amount;
}
public void deposit(double amount) {
We assume that all
balance += amount; required setters and
} getters are defined
public void withdraw(double amount) {
balance -= amount;
}
}

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.4 Example with inheritance
public class CheckingAccount extends Account {
private boolean overdrawn;

public CheckingAccount(String name, long number, double amount) {


super(“Checking account”, name, number, amount);
overdrawn = false;
}
}

No need to define setters


and getters of this class
because it inherits them
from the superclass

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.4 Example with inheritance (Cont.)
public class SavingAccount extends Account {
private double interestRate = 0.10;

public SavingAccount(String name, long number, double amount) {


super(“Saving account”, name, number, amount);
}
}

No need to define setters


and getters of this class
because it inherits them
from the superclass

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.4 Example with inheritance (Cont.)
public class TestAccount {
public static void main (String[] args){
SavingAccount sa= new SavingAccount("Saleh", 1111, 10000.0);
System.out.println( "account type: " + sa.getType());
System.out.println( "account name: " + sa.getName() );
System.out.println( "initial amount: " + sa.getBalance() );
sa.deposit(5000);
System.out.println( "new amount after deposit: "+sa.getBalance());

CheckingAccount ca= new CheckingAccount("Ahmad", 2222, 20000.0);


System.out.println( "account type: " + ca.getType());
System.out.println( “account name: “ + ca.getName() );
System.out.println( “initial amount:“ + ca.getBalance() );
ca.deposit(6000);
System.out.println(“new amount after deposit: “+ca.getBalance());
ca.withdraw(3000);
System.out.println(“new amount after withdrawal: “ + ca.getBalance());
}
}
© Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.4 Example output

account type: Saving account


account name: Saleh
initial amount: 10000.0
new amount after deposit: 15000.0
account type: Checking account
account name: Ahmad
initial amount: 20000.0
new amount after deposit: 26000.0
new amount after withdrawal: 23000.0

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.5 Inheritance advantages
🞂 Reusability: If duplicate code (variable and methods) exists
in two related classes, we can refactored that hierarchy by
moving that common code up to the common superclass
🞂 Organization: Moving of common code to superclass results
in better organization of code.
🞂 Data hiding: base class can decide to keep some data private
so that it cannot be altered by the derived class
🞂 Overriding: With inheritance, we will be able to override the
methods of the base class so that meaningful implementation
of the base class method can be designed in the derived class

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.6 Overriding
🞂 A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a
method defined in the superclass. This is referred to as method
overriding.

public class Circle extends GeometricObject {


// Other methods are omitted

/** Override the toString method defined in


GeometricObject */
public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
© Copyright 1992-2015 by Pearson Education,
Inc. All Rights Reserved.
5.6 Overriding(Cont.)
🞂 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.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.6 Overriding vs. Overloading

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.6 Overriding(Cont.)
🞂 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.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.7 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.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.8 The toString() method in Object
🞂 The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
(@), and a number representing this object.

Loan loan = new Loan();


System.out.println(loan.toString());

🞂 The code displays something like Loan@15037e5 . This


message is not very helpful or informative. Usually you
should override the toString method so that it returns a
digestible string representation of the object.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
Inheritance – Part 2

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.


Superclass and Subclasses Example
public class Shape {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
public Shape() {
dateCreated = new java.util.Date(); }
/** Construct a geometric object with color and
filled value */
protected Shape (String color, boolean filled) {
dateCreated = new java.util.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; }
/** Return filled. Since filled is boolean,
* the get method is named isFilled */
public boolean isFilled() {
return filled; }
/** Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled; }
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated; }
@Override
public String toString() {
return "created on " + dateCreated + "\
ncolor: " + color +" and filled: " + filled;
}
/** getArea method */
public double getArea() { return 0.0; }
/** getPerimeter method */
public double getPerimeter () { return 0.0; }
}
public class Circle extends Shape {
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);
setFilled(filled);
}
/** Return radius */
public double getRadius() { return radius; }
/** Set a new radius */
public void setRadius(double radius){
this.radius = radius; }
/** 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);
}
}
public class Rectangle extends Shape {
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;
setColor(color);
setFilled(filled);
}
/** Return width */
public double getwidth() { return width; }
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);}
}
public class TestShape {
public static void main(String[] args) {
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());
}
}
A circle created on Sun Jan 29 23:17:38 AST 2023
color: white and filled: false
The color is white
The radius is 1.0
The area is 3.141592653589793
The diameter is 2.0

A rectangle created on Sun Jan 29 23:17:38 AST 2023


color: white and filled: false
The area is 8.0
The perimeter is 12.0
5.13 Are superclass’s Constructor
Inherited?
🞂 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.

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.14 Superclass’s Constructor Is
Always Invoked
🞂 A constructor may invoke an overloaded constructor or its superclass’s
constructor. If none of them is invoked explicitly, the compiler puts
super() as the first statement in the constructor. For example,

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.15 Using the Keyword super
🞂 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

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

© Copyright 1992-2015 by Pearson Education,


Inc. All Rights Reserved.
5.16 Constructor Chaining
🞂 Constructing an instance of a class invokes all the superclasses’
constructors along the inheritance chain. This is known as constructor
chaining.
5.17 Calling Superclass Methods

🞂 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);
}
5.18 The protected Modifier

🞂 The protected modifier can be applied on data and methods in a class.


A protected data or a protected method in a public class can be
accessed by any class in the same package or its subclasses, even if the
subclasses are in a different package.
🞂 private, default, protected, and public
5.19 Accessibility Summary
5.20 Visibility Modifiers
5.21 A Subclass Cannot Weaken the Accessibility

🞂 A subclass may override a protected method in its


superclass and change its visibility to public.
However, a subclass cannot weaken the accessibility
of a method defined in the superclass. For example, if
a method is defined as public in the superclass, it
must be defined as public in the subclass.

You might also like