chapter 04 inheritance
Post on 29-Nov-2014
2.197 Views
Preview:
DESCRIPTION
TRANSCRIPT
Chapter 04: Inheritance
1
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
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
Concept of Inheritance
4
5
6
• Use inheritance to create derived class
▫ Save time
▫ Reduce errors
▫ Reduce amount of new learning required to use new
class
7
• Base class
▫ Used as a basis for inheritance
▫ Also called:
� Superclass
� Parent class� Parent class
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
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
Extending Classes
10
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.
Extra notes
12
Inheritance Relationship• The inheritance relationship can be viewed as a
relationship between an object category and its
subcategories.
▫ For example...
Transport
Inheritance Relationship
Air Transport
Transport
Inheritance Relationship
Air Transport
Transport
Inheritance Relationship
Sea
Transport
Air Transport
Transport
Inheritance Relationship
Sea
Transport
Land Transport
Inheritance Relationship
• The inheritance relationship is sometimes
called the “is-a” relationship.
▫ For example...▫ For example...
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
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.
Inheritance Relationship
Transport
speed
getSpeed( )
Attributes
speed
altitude
Air Transport
altitude
fly( )
getSpeed()
Behaviour
fly()
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.
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
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.
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() {…}
}}
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.
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
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.
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) {
^
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.
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.
Method Overriding• A subclass sometimes inherits instance
methods whose implementation is not
suitable for its instances.
For example …
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.
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
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 …
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
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
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();
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;
}
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("=================");
}
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=================
• 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?
• 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("=================");
}
top related