43
Chapter 04: Inheritance 1 Chapter 04: Inheritance

Chapter 04 inheritance

Embed Size (px)

DESCRIPTION

not 100% wrote by the author.just to share.

Citation preview

Page 1: Chapter 04 inheritance

Chapter 04: Inheritance

1

Chapter 04: Inheritance

Page 2: Chapter 04 inheritance

2

Objectives• Learn about the concept of inheritance

• Extend classes

• Override superclass methods

• Understand how constructors are called during • Understand how constructors are called during

inheritance

• Use superclass constructors that require arguments

• Access superclass methods

• Learn which methods you cannot override

Page 3: Chapter 04 inheritance

3

Learning About the Concept

of Inheritance• Inheritance

▫ Mechanism that enables one class to inherit behavior

and attributes of another classand attributes of another class

▫ Apply knowledge of general category to more specific

objects

Page 4: Chapter 04 inheritance

Concept of Inheritance

4

Page 5: Chapter 04 inheritance

5

Page 6: Chapter 04 inheritance

6

• Use inheritance to create derived class

▫ Save time

▫ Reduce errors

▫ Reduce amount of new learning required to use new

class

Page 7: Chapter 04 inheritance

7

• Base class

▫ Used as a basis for inheritance

▫ Also called:

� Superclass

� Parent class� Parent class

Page 8: Chapter 04 inheritance

8

Learning About the Concept

of Inheritance (continued)• Derived class

▫ Inherits from a base class

▫ Always “is a” case or example of more general base ▫ Always “is a” case or example of more general base

class

▫ Also called:

� Subclass

� Child class

Page 9: Chapter 04 inheritance

9

Extending Classes

• Keyword extends

▫ Achieve inheritance in Java

▫ Example: ▫ Example: public class EmployeeWithTerritory

extends Employee

• Inheritance one-way proposition

▫ Child inherits from parent, not other way around

• Subclasses more specific

• instanceof keyword

Page 10: Chapter 04 inheritance

Extending Classes

10

Page 11: Chapter 04 inheritance

Quick Quiz

11

1. ____ is the principle that allows you to apply

your knowledge of a general category to more

specific objects.

2. True or False: A class diagram consists of a 2. True or False: A class diagram consists of a

rectangle divided into five sections.

3. You use the keyword ____ to achieve inheritance

in Java.

Page 12: Chapter 04 inheritance

Extra notes

12

Page 13: Chapter 04 inheritance

Inheritance Relationship• The inheritance relationship can be viewed as a

relationship between an object category and its

subcategories.

▫ For example...

Page 14: Chapter 04 inheritance

Transport

Inheritance Relationship

Page 15: Chapter 04 inheritance

Air Transport

Transport

Inheritance Relationship

Page 16: Chapter 04 inheritance

Air Transport

Transport

Inheritance Relationship

Sea

Transport

Page 17: Chapter 04 inheritance

Air Transport

Transport

Inheritance Relationship

Sea

Transport

Land Transport

Page 18: Chapter 04 inheritance

Inheritance Relationship

• The inheritance relationship is sometimes

called the “is-a” relationship.

▫ For example...▫ For example...

Page 19: Chapter 04 inheritance

Transport

Inheritance Relationship

Inheritance Relationship

Sea Transport Land Transport Air Transport

Sea Transport

object “is a”

Transport object

Land Transport

object “is a”

Transport object

Air Transport

object “is a”

Transport object

Page 20: Chapter 04 inheritance

Inheritance Relationship• Based on the meaning of the “is-a” relationship,

each object will have attributes and behaviour as

defined by its category and all its supercategories.

• An inheritance hierarchy can be built through

generalization or specialization.

Page 21: Chapter 04 inheritance

Inheritance Relationship

Transport

speed

getSpeed( )

Attributes

speed

altitude

Air Transport

altitude

fly( )

getSpeed()

Behaviour

fly()

Page 22: Chapter 04 inheritance

Subclassing• Java supports class inheritance through

subclassing.

• By declaring a class as a subclass of a base class, an • By declaring a class as a subclass of a base class, an

inheritance relationship between those two classes

is created.

• The Java keyword for this is extends.

Page 23: Chapter 04 inheritance

class Rectangle {

public Rectangle(int w, int h) {width = w;height = h;

private int width, height;

Subclassing

class Square extends Rectangle {

}

}

height = h;}

public int getArea() {return width * height;

}

subclassBase class

Page 24: Chapter 04 inheritance

Subclassing• In the example, the Square class is declared as a

subclass of the Rectangle class

• Each subclass inherits the instance variables and

instance methods of its base class.

• Note that constructors and private methods ARE NOT

INHERITED.

• Besides attributes and methods inherited from its base

class, a subclass can also define its own attributes and

methods.

Page 25: Chapter 04 inheritance

class AudioPlayer {class AudioPlayer {private String audioFilename;private String audioFilename;public AudioPlayer() {…}public AudioPlayer() {…}public void play() {…}public void play() {…}private void convert() {…}private void convert() {…}

}}

class AudioPlayer {class AudioPlayer {private String audioFilename;private String audioFilename;public AudioPlayer() {…}public AudioPlayer() {…}public void play() {…}public void play() {…}private void convert() {…}private void convert() {…}

}}

Subclassing

Attributes:

Constructor:

Instance method:

audioFilenameencrypted

MP3Player()

play()

class MP3Player extends AudioPlayer {class MP3Player extends AudioPlayer {private boolean encrypted;private boolean encrypted;public MP3Player() {…}public MP3Player() {…}

}}

: MP3Player

}}

class MP3Player extends AudioPlayer {class MP3Player extends AudioPlayer {private boolean encrypted;private boolean encrypted;public MP3Player() {…}public MP3Player() {…}

}}

Page 26: Chapter 04 inheritance

Constructors and super()• Although a subclass inherits private attributes from its

base class, it has no direct access to them. How will the

subclass be able to initialize those attributes in its

constructors? constructors?

• Every constructor defined in a subclass must “call” one

of the constructors of its base class. The “call” is

performed through the super() statement.

• The super() statement must be the first statement in the constructor method.

Page 27: Chapter 04 inheritance

class Rectangle {

public Rectangle(int w, int h) {width = w;height = h;

}

private int width, height;

Constructors and super()

}

}

public int getArea() {return width * height;

}

class Square extends Rectangle {

}

public Square(int size) {super(size, size);

}

“Calls” the constructor of the Rectangle class

Page 28: Chapter 04 inheritance

Constructors and super()• Note that if there is no super() statement in

a constructor, the compiler will automatically

insert a super() statement with no insert a super() statement with no parameters.

Page 29: Chapter 04 inheritance

class Square extends Rectangle{

public Square(int size) {setWidth(size);setHeight(size);

}

class Rectangle {

public Rectangle(int w, int h) {width = w;height = h;

private int width, height;

Constructors and super()

}

}

height = h;}

public void setHeight(int h) {height = h;

}

public void setWidth(int w) {width = w;

}

Compiler secretly adds

a super()!

The compiler then displays this error

message. Why?test.java: 16: cannot resolve symbolsymbol : constructor Rectangle ()location: class Rectanglepublic Square(int size) {

^

Page 30: Chapter 04 inheritance

Benefits of Inheritance

• Reduces redundant code and code modifications

▫ A base class defines attributes and methods which

are inherited by all of its subclasses. This leads to a

reduction of redundant code and code reduction of redundant code and code

modifications.

• Makes your program easier to extend

▫ When adding a new subclass, we only need to define

attributes and methods which are specific to objects

of that class.

Page 31: Chapter 04 inheritance

Benefits of Inheritance

• Increases code reuse

▫ Example: The Java library has a JButton class. We

can create a subclass of the JButton class to define

objects which are like JButton objects but with objects which are like JButton objects but with additional attributes and methods.

▫ This is possible even though we do not have access

to the source code for the JButton class.

Page 32: Chapter 04 inheritance

Method Overriding• A subclass sometimes inherits instance

methods whose implementation is not

suitable for its instances.

For example …

Page 33: Chapter 04 inheritance

class Circle {

}

public Circle(int r) {radius = r;

}

private int radius;

public double getArea( ) {System.out.print("(Area calculated in Circle::getArea()) ");return 22.0/7*radius*radius;

}}

class Point extends Circle {

}

public Point(int px, int py) {

super(0);x = px;y = py;

}

private int x, y;The Point class inherits

the radius attribute and

the getArea() method

from its base class.

Page 34: Chapter 04 inheritance

class Application {

}

public static void main(String[ ] args) {Circle circle = new Circle(7);Point pt = new Point(100, 50);System.out.println(“Area of circle: "+circle.getArea());System.out.println("Area of point: "+pt.getArea());

}

• The area for any Point object is zero. For efficiency, it is unnecessary to calculate the area; simply return

the value 0.

Output:(Area calculated in Circle::getArea()) Area of circle: 154.0(Area calculated in Circle::getArea()) Area of point: 0.0

Page 35: Chapter 04 inheritance

Method Overriding• Java supports method overriding. Method

overriding means replacing the

implementation of an inherited method with

another implementation.another implementation.

• To override a method, we simply redefine the

method in the subclass.

• For example …

Page 36: Chapter 04 inheritance

class Point extends Circle {

class Circle {

}

public Circle(int r) {radius = r;

}

private int radius;

public double getArea( ) {System.out.print("(Area calculated in Circle::getArea()) ");return 22.0/7*radius*radius;

}

class Point extends Circle {

}

public Point(int px, int py) {super(0);x = px;y = py;

}

private int x, y;

public double getArea( ) {System.out.print("(Area calculated in Point::getArea()) ");return 0;

}

Method getArea()overriden

Returns 0

Page 37: Chapter 04 inheritance

class Application {

public static void main(String[ ] args) {Circle circle = new Circle(7);Point pt = new Point(100, 50);System.out.println(“Area of circle: "+circle.getArea());

Method Overriding

}

System.out.println(“Area of circle: "+circle.getArea());System.out.println("Area of point: "+pt.getArea());

}

Output:(Area calculated in Circle::getArea()) Area of circle: 154.0(Area calculated in Point::getArea()) Area of point: 0.0

Page 38: Chapter 04 inheritance

A

doThis() D objD = new D();E objE = new E();B objB = new B();

Method Overriding• Consider the following inheritance hierarchy:

D C

doThis()

E

doThis()

F

B

B objB = new B();objE.doThis();objD.doThis();objB.doThis();

Page 39: Chapter 04 inheritance

The super keyword again…• Consider the following class definitions:

class Rectangle {…private int width, height;

public Rectangle(int w, int h) {width = w;

…}

public void display( ) {for (int row=0; row < height; row++) {

for (int col=0; col < width; col++)System.out.print('*');

System.out.println();}

}

width = w;height = h;

}

Page 40: Chapter 04 inheritance

class LabelledRectangle extends Rectangle {

public LabelledRectangle(int w, int h, String str) {super(w, h);label = str;

}

private String label;

public void display( ) {

Overrides display()

method inherited from

the base class

Rectangle class is

the base class for

this subclass

…}

public void display( ) {System.out.println("=================");for (int row=0; row < height; row++) {

for (int col=0; col < width; col++)System.out.print('*');

System.out.println();}System.out.println(label);System.out.println("=================");

}

Page 41: Chapter 04 inheritance

class Application {

public static void main(String[ ] args) {Rectangle rect1 = new Rectangle(3, 3);LabelledRectangle rect2;rect2 = new LabelledRectangle(2, 3, "Block");rect1.display();System.out.println();

Method Overriding

}

System.out.println();rect2.display();

}

*********=================******Block=================

Page 42: Chapter 04 inheritance

• Observe the body of the display() method in the LabelledRectangle class…

public void display( ) {System.out.println("=================");for (int row=0; row < getHeight(); row++) {

for (int col=0; col < getWidth(); col++)System.out.print('*');

System.out.println();

Exactly the same as

the code in the

display() method

inherited from the

base class

System.out.println();}System.out.println(label);System.out.println("=================");

}

� Is it possible to “call” the

overridden display() method

in the Rectangle class?

Page 43: Chapter 04 inheritance

• We can “call” the overridden method by using the

super keyword as follows:

class LabelledRectangle extends Rectangle {

public LabelledRectangle(int w, int h, String str) {super(w, h);label = str;

private String label;

Executes the

overridden method

}

label = str;}

public void display( ) {System.out.println("=================");super.display();System.out.println(label);System.out.println("=================");

}