0% found this document useful (0 votes)
10 views93 pages

Specialized Classes in Inheritance

Chapter 10 covers the concept of inheritance in object-oriented programming, explaining the 'is a' relationship between superclasses and subclasses, and how subclasses inherit fields and methods from superclasses. It discusses calling superclass constructors, overriding methods, and the implications of access modifiers on inheritance. Additionally, it introduces abstract classes, interfaces, and practical examples of inheritance in Java.

Uploaded by

danil.buzhor2012
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views93 pages

Specialized Classes in Inheritance

Chapter 10 covers the concept of inheritance in object-oriented programming, explaining the 'is a' relationship between superclasses and subclasses, and how subclasses inherit fields and methods from superclasses. It discusses calling superclass constructors, overriding methods, and the implications of access modifiers on inheritance. Additionally, it introduces abstract classes, interfaces, and practical examples of inheritance in Java.

Uploaded by

danil.buzhor2012
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 10

Inheritance

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


Chapter Topics
Chapter 10 discusses the following main topics:
– What Is Inheritance?
– Calling the Superclass Constructor
– Overriding Superclass Methods
– Protected Members
– Chains of Inheritance
– The Object Class
– Polymorphism
– Abstract Classes and Abstract Methods
– Interfaces
– Anonymous Classes
– Functional Interfaces and Lambda Expressions

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-2
What is Inheritance?
Generalization vs. Specialization

• Real-life objects are typically specialized versions of


other more general objects.
• The term “insect” describes a very general type of
creature with numerous characteristics.
• Grasshoppers and bumblebees are insects
– They share the general characteristics of an insect.
– However, they have special characteristics of their own.
• grasshoppers have a jumping ability, and
• bumblebees have a stinger.
• Grasshoppers and bumblebees are specialized versions
of an insect.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-3
Inheritance

Insect
Contains those attributes
and methods that are
shared by all insects.

BumbleBee Grasshopper

Contains those attributes and Contains those attributes and


methods that specific to a methods that are specific to a
Bumble Bee. Grasshopper.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-4
The “is a” Relationship
• The relationship between a superclass and an inherited
class is called an “is a” relationship.
– A grasshopper “is a” insect.
– A poodle “is a” dog.
– A car “is a” vehicle.
• A specialized object has:
– all of the characteristics of the general object, plus
– additional characteristics that make it special.
• In object-oriented programming, inheritance is used to
create an “is a” relationship among classes.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-5
The “is a” Relationship
• We can extend the capabilities of a class.
• Inheritance involves a superclass and a subclass.
– The superclass is the general class and
– the subclass is the specialized class.
• The subclass is based on, or extended from, the superclass.
– Superclasses are also called base classes, and
– subclasses are also called derived classes.
• The relationship of classes can be thought of as parent classes
and child classes.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-6
Inheritance
• The subclass inherits fields and methods from the
superclass without any of them being rewritten.
• New fields and methods may be added to the subclass.
• The Java keyword, extends, is used on the class header
to define the subclass.

public class FinalExam extends GradedActivity

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-7
The GradedActivity Example
GradedActivity
Contains those attributes and methods
- score : double that are shared by all graded activities.

+ setScore(s : double) : void Contains those attributes and methods


+ getScore() : double that are specific to the FinalExam
+ getGrade() : char class.
Inherits all non-private attributes and
methods from the GradedActivity
class.
FinaExam
- numQuestions : int • Example:
- pointsEach : double
- numMissed : int – [Link],
+ FinalExam(questions : int, – [Link],
missed : int) – [Link],
+ getPointsEach() : double
+ getNumMissed() : int – [Link]
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-8
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016
public class FinalExam extends GradedActivity
{
private int numQuestions; // # of questions
private double pointsEach; // Points for each
private int numMissed; // Questions missed
public FinalExam(int questions, int missed)
{
double numericScore; // for numeric score
numQuestions = questions;
numMissed = missed;
pointsEach = 100.0 / questions;
numericScore= 100.0 - (missed * pointsEach);
setScore(numericScore);
}
public double getPointsEach()
{
return pointsEach;
}
public int getNumMissed()
{
return numMissed;
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class FinalExamDemo
{
public static void main(String[] args)
{
String input; // To hold input
int questions; // Number of questions
int missed; // Number of questions missed
input = [Link]("How many questions are on the final exam?");
questions = [Link](input);
input = [Link]("How many " +
"questions did the student miss?");
missed = [Link](input);
FinalExam exam = new FinalExam(questions, missed);
[Link](null,
"Each question counts " + [Link]() +
" points.\nThe exam score is " + [Link]() + "\nThe exam grade is " +
[Link]());
[Link](0);
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Inheritance, Fields and Methods
• Members of the superclass that are marked private:
– are not inherited by the subclass,
– exist in memory when the object of the subclass is created
– may only be accessed from the subclass by public methods
of the superclass.
• Members of the superclass that are marked public:
– are inherited by the subclass, and
– may be directly accessed from the subclass.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-12
Inheritance, Fields and Methods
• When an instance of the subclass is created, the non-private
methods of the superclass are available through the subclass
object.

FinalExam exam = new FinalExam();


[Link](85.0);
[Link]("Score = "
+ [Link]());

• Non-private methods and fields of the superclass are available


in the subclass.

setScore(newScore);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-13
Inheritance and Constructors
• Constructors are not inherited.
• When a subclass is instantiated, the superclass default
constructor is executed first.
• Example:
– [Link]
– [Link]
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-14
public class SuperClass1
{
public SuperClass1()
{
[Link]("This is the superclass constructor.");
}
}
public class SubClass1 extends SuperClass1
{
public SubClass1()
{
[Link]("This is the subclass constructor.");
}
}
public class ConstructorDemo1
{
public static void main(String[] args)
Output {
This is the superclass constructor. SubClass1 obj = new SubClass1();
This is the subclass constructor. }
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Superclass’s Constructor
• The super keyword refers to an object’s superclass.
• The superclass constructor can be explicitly called
from the subclass by using the super keyword.
• Example:
– [Link], [Link], [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-16
public class SuperClass2
{
public SuperClass2()
{
[Link]("This is the superclass no-arg constructor.");
}
public SuperClass2(int arg)
{
[Link]("The following argument was passed to the “ +
"superclass constructor: " + arg);
}
}

public class SubClass2 extends SuperClass2 public class ConstructorDemo2


{ {
public SubClass2() public static void main(String[] args)
{ {
super(10); SubClass2 obj = new SubClass2();
[Link]("This is the “ + }
“subclass constructor."); }
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Calling The Superclass Constructor
• If a parameterized constructor is defined in the
superclass,
– the superclass must provide a no-arg constructor, or
• subclasses must provide a constructor, and
• subclasses must call a superclass constructor.
• Calls to a superclass constructor must be the first
java statement in the subclass constructors.
• Example:
– [Link], [Link], [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-18
public class Rectangle public void setWidth(double w)
{ {
private double length; width = w;
private double width; }
public Rectangle(double len, double w) public double getLength()
{ {
length = len; return length;
width = w; }
} public double getWidth()
public Rectangle () {
{ return width;
length = 1 ; }
width = 1 ; public double getArea()
} {
public void setLength(double len) return length * width;
{ }
length = len; } // end of class
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class Cube extends Rectangle public double getVolume()
{ {
private double height; // cube's height return getArea() * height;
}
public Cube(double len, double w, } // end of class
double h)
{
// Call the superclass constructor.
super(len, w);

// Set the height.


height = h;
}
public double getHeight()
{
return height;
}
public double getSurfaceArea()
{
return getArea() * 6;
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class CubeDemo
{
public static void main(String[] args)
{
double length, width, height;
Scanner keyboard = new Scanner([Link]);
[Link]("Enter the following dimensions of a cube:");
[Link]("Length: ");
length = [Link]();
[Link]("Width: ");
width = [Link]();
[Link]("Height: ");
height = [Link]();
Cube myCube = new Cube(length, width, height);
[Link]("Here are the cube's properties.");
[Link]("Length: " + [Link]());
[Link]("Width: " + [Link]());
[Link]("Height: " + [Link]());
[Link]("Base Area: " + [Link]());
[Link]("Surface Area: " + [Link]());
[Link]("Volume: " + [Link]());
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Overriding Superclass Methods
• A subclass may have a method with the same
signature as a superclass method.
• The subclass method overrides the superclass
method.
• This is known as method overriding.
• Example:
– [Link], [Link],
[Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-22
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016
public class CurvedActivity extends GradedActivity
{
double rawScore; // Unadjusted score
double percentage; // Curve percentage
public CurvedActivity(double percent)
{
percentage = percent;
rawScore = 0.0;
}
public void setScore(double s)
{
rawScore = s;
[Link](rawScore * percentage);
}
public double getRawScore()
{
return rawScore;
}
public double getPercentage()
{
return percentage;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
import [Link];
public class CurvedActivityDemo
{
public static void main(String[] args)
{
double score; // Raw score
double curvePercent; // Curve percentage
Scanner keyboard = new Scanner([Link]);
[Link]("Enter the student's raw numeric score: ");
score = [Link]();
[Link]("Enter the curve percentage: ");
curvePercent = [Link]();
CurvedActivity curvedExam = new CurvedActivity(curvePercent);
[Link](score);
[Link]("The raw score is " +
[Link]() + " points.");
[Link]("The curved score is " +
[Link]());
[Link]("The exam grade is " +
[Link]());
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Overriding Superclass Methods
GradedActivity
- score : double
+ setScore(s : double) : void
+ getScore() : double
+ getGrade() : char

This method is a more specialized


version of the setScore method in
CurvedActivity
the superclass, GradedActivity.
- rawScore : double
- percentage : double
+ CurvedActivity
(percent : double)
+ setScore(s : double) : void
+ getRawScore() : double
+ getPercentage() : double

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-26
Overriding Superclass Methods
• Recall that a method’s signature consists of:
– the method’s name
– the data types method’s parameters in the order that they
appear.
• A subclass method that overrides a superclass method must
have the same signature as the superclass method.
• An object of the subclass invokes the subclass’s version of the
method, not the superclass’s.
• The @Override annotation should be used just before the
subclass method declaration.
– This causes the compiler to display a error message if the
method fails to correctly override a method in the superclass.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-27
Overriding Superclass Methods
• An subclass method can call the overridden superclass method
via the super keyword.

[Link](rawScore * percentage);

• There is a distinction between overloading a method and


overriding a method.
• Overloading is when a method has the same name as one or
more other methods, but with a different signature.
• When a method overrides another method, however, they both
have the same signature.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-28
Overriding Superclass Methods
• Both overloading and overriding can take place in an
inheritance relationship.
• Overriding can only take place in an inheritance
relationship.
• Example:
– [Link],
– [Link],
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-29
public class SuperClass3
{
public void showValue(int arg)
{
[Link]("SUPERCLASS: The int argument was " + arg);
}
public void showValue(String arg)
{
[Link]("SUPERCLASS: The String argument was " + arg);
}
}

public class SubClass3 extends SuperClass3


{
public void showValue(int arg)
{
[Link]("SUBCLASS: The int argument was " + arg);
}
public void showValue(double arg)
{
[Link]("SUBCLASS: The double argument was " + arg);
}
} ©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class ShowValueDemo
{
public static void main(String[] args)
{
// Create a SubClass3 object.
SubClass3 myObject = new SubClass3();

[Link](10); // Pass an int.


[Link](1.2); // Pass a double.
[Link]("Hello"); // Pass a String.
}
}

Output
SUBCLASS: The int argument was 10
SUBCLASS: The double argument was 1.2
SUPERCLASS: The String argument was Hello

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Preventing a Method from Being
Overridden
• The final modifier will prevent the overriding of a
superclass method in a subclass.

public final void message()

• If a subclass attempts to override a final method, the


compiler generates an error.
• This ensures that a particular superclass method is used
by subclasses rather than a modified version of it.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-32
Protected Members
• Protected members of class:
– may be accessed by methods in a subclass, and
– by methods in the same package as the class.
• Java provides a third access specification,
protected.
• A protected member’s access is somewhere between
private and public.
• Example:
– [Link]
– [Link]
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-33
public class GradedActivity2
{
protected double score; // Numeric score
public void setScore(double s)
{
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
} ©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class FinalExam2 extends GradedActivity2
{
private int numQuestions; // Number of questions
private double pointsEach; // Points for each question
private int numMissed; // Number of questions missed
public FinalExam2(int questions, int missed)
{
double numericScore; // To hold a numeric score
numQuestions = questions;
numMissed = missed;
pointsEach = 100.0 / questions;
numericScore = 100.0 - (missed * pointsEach);
setScore(numericScore);
adjustScore();
}
public double getPointsEach()
{
return pointsEach;
}
public int getNumMissed()
{
return numMissed;
}
private void adjustScore()
{
double fraction;
fraction = score - (int) score;
if (fraction >= 0.5)
score = score + (1.0 - fraction);
}
} ©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
import [Link];
public class ProtectedDemo
{
public static void main(String[] args)
{
String input; // To hold input
int questions; // Number of questions
int missed; // Number of questions missed
input = [Link]("How many " +
"questions are on the final exam?");
questions = [Link](input);
input = [Link]("How many " +
"questions did the student miss?");
missed = [Link](input);
FinalExam2 exam = new FinalExam2(questions, missed);
[Link](null,
"Each question counts " + [Link]() +
" points.\nThe exam score is " +
[Link]() + "\nThe exam grade is " +
[Link]());
[Link](0);
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Protected Members
• Using protected instead of private makes some tasks
easier.
• However, any class that is derived from the class, or is in the
same package, has unrestricted access to the protected
member.
• It is always better to make all fields private and then
provide public methods for accessing those fields.
• If no access specifier for a class member is provided, the class
member is given package access by default.
• Any method in the same package may access the member.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-37
Access Specifiers
Accessible to a subclass inside Accessible to all other classes
Access Modifier
the same package? inside the same package?
default
Yes Yes
(no modifier)
Public Yes Yes
Protected Yes Yes
Private No No

Accessible to a subclass Accessible to all other classes


Access Modifier
outside the package? outside the package?
default
No No
(no modifier)
Public Yes Yes
Protected Yes No
Private No No

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-38
Chains of Inheritance

• A superclass can also be derived from another


class. Object

Example:
[Link]
GradedActivity
[Link]
[Link]
[Link]
PassFailActivity

PassFailExam

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-39
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016
public class PassFailActivity extends GradedActivity
{
private double minPassingScore; // Minimum passing score
public PassFailActivity(double mps)
{
minPassingScore = mps;
}
public char getGrade()
{
char letterGrade;

if ([Link]() >= minPassingScore)


letterGrade = 'P';
else
letterGrade = 'F';

return letterGrade;
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class PassFailExam extends PassFailActivity
{
private int numQuestions; // Number of questions
private double pointsEach; // Points for each question
private int numMissed; // Number of questions missed
public PassFailExam(int questions, int missed,
double minPassing)
{
super(minPassing);
double numericScore;
numQuestions = questions;
numMissed = missed;
pointsEach = 100.0 / questions;
numericScore = 100.0 - (missed * pointsEach);
setScore(numericScore);
}
public double getPointsEach()
{
return pointsEach;
}
public int getNumMissed()
{
return numMissed;
}©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
}
import [Link];
public class PassFailExamDemo
{
public static void main(String[] args)
{
int questions; // Number of questions
int missed; // Number of questions missed
double minPassing; // Minimum passing score
Scanner keyboard = new Scanner([Link]);
[Link]("How many questions are on the exam? ");
questions = [Link]();
[Link]("How many questions did the student miss? ");
missed = [Link]();
[Link]("What is the minimum passing score? ");
minPassing = [Link]();
PassFailExam exam =
new PassFailExam(questions, missed, minPassing);
[Link]("Each question counts " +
[Link]() + " points.");
[Link]("The exam score is " + [Link]());
[Link]("The exam grade is " + [Link]());
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chains of Inheritance
• Classes often are depicted graphically in a class
hierarchy.
• A class hierarchy shows the inheritance
relationships between classes.

GradedActivity

FinalExam PassFailActivity

PassFailExam

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-44
The Object Class
• All Java classes are directly or indirectly derived from a class
named Object.
• Object is in the [Link] package.
• Any class that does not specify the extends keyword is
automatically derived from the Object class.

public class MyClass


{
// This class is derived from Object.
}

• Ultimately, every class is derived from the Object class.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-45
The Object Class
• Because every class is directly or indirectly derived
from the Object class:
– every class inherits the Object class’s members.
• example: toString and equals.
• In the Object class, the toString method returns a
string containing the object’s class name and a hash of
its memory address.
• The equals method accepts the address of an object
as its argument and returns true if it is the same as the
calling object’s address.
• Example: [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-46
public class ObjectMethods
{
public static void main(String[] args)
{
PassFailExam exam1 =
new PassFailExam(0, 0, 0);
PassFailExam exam2 =
new PassFailExam(0, 0, 0);
[Link](exam1);
[Link](exam2);
if ([Link](exam2))
[Link]("They are the same.");
else
[Link]("They are not the same.");
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Polymorphism
• A reference variable can reference objects of classes that are
derived from the variable’s class.
GradedActivity exam;

• We can use the exam variable to reference a GradedActivity


object.
exam = new GradedActivity();

• The GradedActivity class is also used as the superclass for


the FinalExam class.
• An object of the FinalExam class is a GradedActivity
object.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-48
Polymorphism
• A GradedActivity variable can be used to reference a
FinalExam object.
GradedActivity exam = new FinalExam(50, 7);

• This statement creates a FinalExam object and stores the


object’s address in the exam variable.
• This is an example of polymorphism.
• The term polymorphism means the ability to take many forms.
• In Java, a reference variable is polymorphic because it can
reference objects of types different from its own, as long as those
types are subclasses of its type.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-49
Polymorphism
• Other legal polymorphic references:
GradedActivity exam1 = new FinalExam(50, 7);
GradedActivity exam2 = new PassFailActivity(70);
GradedActivity exam3 = new PassFailExam(100, 10, 70);

• The GradedActivity class has three methods:


setScore, getScore, and getGrade.
• A GradedActivity variable can be used to call only those
three methods.
GradedActivity exam = new PassFailExam(100, 10, 70);
[Link]([Link]()); // This works.
[Link]([Link]()); // This works.
[Link]([Link]()); // ERROR!

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-50
Polymorphism and Dynamic Binding
• If the object of the subclass has overridden a method in the
superclass:
– If the variable makes a call to that method the subclass’s version of the
method will be run.
GradedActivity exam = new PassFailActivity(60);
[Link](70);
[Link]([Link]());

• Java performs dynamic binding or late binding when a variable contains a


polymorphic reference.
• The Java Virtual Machine determines at runtime which method to call,
depending on the type of object that the variable references.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-51
Polymorphism
• It is the object’s type, rather than the reference type,
that determines which method is called.
• Example:
– [Link]
• You cannot assign a superclass object to a subclass
reference variable.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-52
public class Polymorphic
{
public static void main(String[] args)
{
GradedActivity[] tests = new GradedActivity[3];
// The first test is a regular exam with a numeric score of 75.
tests[0] = new GradedActivity();
tests[0].setScore(95);

// The second test is a pass/fail test. The student missed 5 out of 20


// questions, and the minimum passing grade is 60.
tests[1] = new PassFailExam(20, 5, 60);

// The third test is the final exam. There were


// 50 questions and the student missed 12.
tests[2] = new FinalExam(50, 7);

// Display the grades.


for (int i = 0; i < [Link]; i++)
{
[Link]("Test " + (i + 1) + ": score " + tests[i].getScore() +
", grade " + tests[i].getGrade());
}
}©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
}
Abstract Classes
• An abstract class cannot be instantiated, but other classes are
derived from it.
• An Abstract class serves as a superclass for other classes.
• The abstract class represents the generic or abstract form of all
the classes that are derived from it.
• A class becomes abstract when you place the abstract key word
in the class definition.

public abstract class ClassName

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-54
Abstract Methods
• An abstract method has no body and must be
overridden in a subclass.
• An abstract method is a method that appears in a
superclass, but expects to be overridden in a subclass.
• An abstract method has only a header and no body.
AccessSpecifier abstract ReturnType MethodName(ParameterList);

• Example:
– [Link], [Link], [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-55
public abstract class Student
{
private String name; // Student name
private String idNumber; // Student ID
private int yearAdmitted; // Year admitted
public Student(String n, String id, int year)
{
name = n;
idNumber = id;
yearAdmitted = year;
}
public String toString()
{
String str;

str = "Name: " + name


+ "\nID Number: " + idNumber
+ "\nYear Admitted: " + yearAdmitted;
return str;
}
public abstract int getRemainingHours();
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class CompSciStudent extends Student
{
// Required hours
private final int MATH_HOURS = 20; // Math hours
private final int CS_HOURS = 40; // Comp sci hours
private final int GEN_ED_HOURS = 60; // Gen ed hours

// Hours taken
private int mathHours; // Math hours taken
private int csHours; // Comp sci hours taken
private int genEdHours; // General ed hours taken

public CompSciStudent(String n, String id, int year)


{
super(n, id, year);

}
public void setMathHours(int math)
{
mathHours = math;
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public void setCsHours(int cs)
{
csHours = cs;
}
public void setGenEdHours(int genEd)
{
genEdHours = genEd;
}
public int getRemainingHours()
{
int reqHours, remainingHours;
reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS;
remainingHours = reqHours - (mathHours + csHours + genEdHours);
return remainingHours;
}
public String toString()
{
String str;
str = [Link]() +
"\nMajor: Computer Science\nMath Hours Taken: " + mathHours +
"\nComputer Science Hours Taken: " + csHours +
"\nGeneral Ed Hours Taken: " + genEdHours;
return str;
}©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
}
public class CompSciStudentDemo
{
public static void main(String[] args)
{
// Create a CompSciStudent object.
CompSciStudent csStudent =
new CompSciStudent("Jennifer Haynes",
"167W98337", 2004);

// Store values for math, CS, and gen ed hours.


[Link](12);
[Link](20);
[Link](40);

// Display the student's data.


[Link](csStudent);

// Display the number of remaining hours.


[Link]("Hours remaining: " +
[Link]());
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Abstract Methods
• Notice that the key word abstract appears in the header, and
that the header ends with a semicolon.

public abstract void setValue(int value);

• Any class that contains an abstract method is automatically


abstract.
• If a subclass fails to override an abstract method, a compiler
error will result.
• Abstract methods are used to ensure that a subclass implements
the method.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-60
Interfaces
• An interface is similar to an abstract class that has all
abstract methods.
– It cannot be instantiated, and
– all of the methods listed in an interface must be written elsewhere.
• The purpose of an interface is to specify behavior for other
classes.
• It is often said that an interface is like a “contract,” and
when a class implements an interface it must adhere to the
contract.
• An interface looks similar to a class, except:
– the keyword interface is used instead of the keyword class,
and
– the methods that are specified in an interface have no bodies, only
headers that are terminated by semicolons.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-61
Interfaces
• The general format of an interface definition:

public interface InterfaceName


{
(Method headers...)
}

• All methods specified by an interface are public by default.


• A class can implement one or more interfaces.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-62
Interfaces
• If a class implements an interface, it uses the
implements keyword in the class header.

public class FinalExam3 extends GradedActivity


implements Relatable

• Example:
– [Link]
– [Link]
– [Link]
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-63
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
score = s;
} public interface Relatable
public double getScore() {
{ boolean equals(GradedActivity g);
return score; boolean isGreater(GradedActivity g);
} boolean isLess(GradedActivity g);
public char getGrade() }
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016
public class FinalExam3 public int getNumMissed()
extends GradedActivity {
implements Relatable return numMissed;
{ }
private int numQuestions; public boolean equals(GradedActivity g)
private double pointsEach; {
private int numMissed; return
public FinalExam3(int questions, [Link]() == [Link]();
int missed) }
{ public boolean isGreater(
double numericScore; GradedActivity g)
numQuestions = questions; {
numMissed = missed; return ([Link]() > [Link]());
pointsEach = 100.0 / questions; }
numericScore = public boolean isLess(GradedActivity g)
100.0 - (missed * pointsEach); {
setScore(numericScore); return ([Link]() < [Link]())
} ;
public double getPointsEach() }
{ }
return pointsEach;
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class InterfaceDemo
{
public static void main(String[] args)
{
FinalExam3 exam1 = new FinalExam3(100, 20);
FinalExam3 exam2 = new FinalExam3(100, 30);

// Display the exam scores


[Link]("Exam 1: " + [Link]());
[Link]("Exam 2: " + [Link]());

// Compare the exam scores.


if ([Link](exam2))
[Link]("The exam scores are equal.");

if ([Link](exam2))
[Link]("The Exam 1 score is the highest.");

if ([Link](exam2))
[Link]("The Exam 1 score is the lowest.");
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Fields in Interfaces
• An interface can contain field declarations:
– all fields in an interface are treated as final and static.
• Because they automatically become final, you must provide an
initialization value.
public interface Doable
{
int FIELD1 = 1, FIELD2 = 2;
(Method headers...)
}
• In this interface, FIELD1 and FIELD2 are final static
int variables.
• Any class that implements this interface has access to these
variables.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-67
Implementing Multiple Interfaces
• A class can be derived from only one superclass.
• Java allows a class to implement multiple interfaces.
• When a class implements multiple interfaces, it must provide
the methods specified by all of them.
• To specify multiple interfaces in a class definition, simply list
the names of the interfaces, separated by commas, after the
implements key word.

public class MyClass implements Interface1,


Interface2,
Interface3

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-68
Interfaces in UML

A dashed line with an arrow


GradedActivity indicates implementation of an
interface.

FinalExam3 Relatable

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-69
Polymorphism with Interfaces
• Java allows you to create reference variables of an interface
type.
• An interface reference variable can reference any object
that implements that interface, regardless of its class type.
• This is another example of polymorphism.
• Example:
– [Link]
– [Link]
– [Link]
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-70
public interface RetailItem public class CompactDisc implements RetailItem
{ {
public double getRetailPrice(); private String title;
private String artist;
}
private double retailPrice;
public CompactDisc(String cdTitle,
String cdArtist, double cdPrice)
{
title = cdTitle;
artist = cdArtist;
retailPrice = cdPrice;
}
public String getTitle()
{
return title;
}
public String getArtist()
{
return artist;
}
public double getRetailPrice()
{
return retailPrice;
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public interface RetailItem public class DvdMovie implements RetailItem
{ {
public double getRetailPrice(); private String title;
private int runningTime;
}
private double retailPrice;
public DvdMovie(String dvdTitle, int runTime,
double dvdPrice)
{
title = dvdTitle;
runningTime = runTime;
retailPrice = dvdPrice;
}
public String getTitle()
{
return title;
}
public int getRunningTime()
{
return runningTime;
}
public double getRetailPrice()
{
return retailPrice;
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class PolymorphicInterfaceDemo
{
public static void main(String[] args)
{
CompactDisc cd =
new CompactDisc("Greatest Hits",
"Joe Looney Band",
18.95);
DvdMovie movie =
new DvdMovie("Wheels of Fury",
137, 12.95);
[Link]("Item #1: " +
[Link]());
showPrice(cd);
[Link]("Item #2: " +
[Link]());
showPrice(movie);
}
private static void showPrice(RetailItem item)
{
[Link]("Price: $%,.2f\n", [Link]());
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Polymorphism with Interfaces
• In the example code, two RetailItem reference variables,
item1 and item2, are declared.
• The item1 variable references a CompactDisc object and
the item2 variable references a DvdMovie object.
• When a class implements an interface, an inheritance
relationship known as interface inheritance is established.
– a CompactDisc object is a RetailItem, and
– a DvdMovie object is a RetailItem.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-74
Polymorphism with Interfaces
• A reference to an interface can point to any class that
implements that interface.
• You cannot create an instance of an interface.

RetailItem item = new RetailItem(); // ERROR!

• When an interface variable references an object:


– only the methods declared in the interface are available,
– explicit type casting is required to access the other methods of an object
referenced by an interface reference.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-75
Default Methods
• Beginning in Java 8, interfaces may have default methods.
• A default method is an interface method that has a body.
• You can add new methods to an existing interface without
causing errors in the classes that already implement the
interface.

• Example:
– [Link]
– [Link]
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public interface Displayable
{
default void display()
{
[Link]("This is the
default display method.");
}
}
public class Person implements Displayable
{
private String name;
public Person(String n)
{
name = n;
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public class InterfaceDemoDefaultMethod
{
public static void main(String[] args)
{
// Create an instance of Person class.
Person p = new Person("Antonio");

// Call the object's display method.


[Link]();
}
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Anonymous Inner Classes
• An inner class is a class that is defined inside another class.
• An anonymous inner class is an inner class that has no name.
• An anonymous inner class must implement an interface, or
extend another class.
• Useful when you need a class that is simple, and to be
instantiated only once in your code.

• Example:
– [Link]
– [Link]

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
interface IntCalculator
{
int calculate(int number);
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public static void main(String[] args)
{
int num;

Scanner keyboard = new Scanner([Link]);


IntCalculator square = new IntCalculator()
{
public int calculate(int number)
{
return number * number;
}
};
[Link]("Enter anumber: ");
num = [Link]();
[Link]("The square is " +
[Link](num));
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Anonymous Inner Classes
• If the anonymous inner class extends a
superclass, the superclass no-arg constructor is
called when the object is created.
• An anonymous inner class must override all
abstract methods of its parent interface or class.
• Because an anonymous inner class is written
inside a method, it can access that method local
variables, but only if they are declare final or
are effectively final.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Functional Interfaces and Lambda
Expressions
• A functional interface is an interface that has one abstract
method.
• A lambda expression can be used to create an object that
implements the interface, and overrides its abstract method.
• In Java 8, these features work together to simplify code,
particularly in situations where you might use anonymous inner
classes.

• Example:
– [Link]
– [Link]
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public static void main(String[] args)
{
int num;
Scanner keyboard = new Scanner([Link]);
IntCalculator square = x -> x * x;
[Link]("Enter a number: ");
num = [Link]();
[Link]("The square is " +
[Link](num));
}

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Lambda Expressions
• You can think of a lambda expression as an
anonymous method, or a method with no name.
• Like regular methods, lambda expressions can
accept arguments and return values.
• The general format is
parameter -> expression
• For example:
x -> x * x
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Lambda Expressions
• We can use a lambda expression to create an
object that implements the IntCaculator interface:
IntCalculator square = x -> x * x;
• Because the IntCalculator interface has only one
abstract method (named calculate), the lambda
expression will be used to implement that one
method.
• We don’t have to specify the type of x because
the compiler will determine it.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Lambda Expressions that Do Not Return
a Value
x -> [Link] (x) ;

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Lambda Expressions with Multiple
Parameters
• If the functional interface abstract method has
multiple parameters, any lambda expression
that you use with the interface must also have
multiple parameters.
(a,b) -> a + b ;

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Lambda Expression with No Parameters
() -> [Link] () ;

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Explicitly Declaring a Parameter Data
Type
• You do not have to specify the data type of a
lambda expression parameter, but you can if
you wish.
(int x) -> x * x ;

(int a, int b) -> a + b ;

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Multiple Statements in Body of Lambda
Expression
• You can write multiple statement in the body of
a lambda expression, but if you do, you must
enclose the statements in a set of curly braces,
and you must write a return statement if the
expression returns a value.
(int x) -> {
int a = x * 2 ;
return a ;
} ;
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Accessing Variables within a Lambda
Expression
• A lambda expression can access variables that
are declared in the enclosing scope, but only if
those variables are final or effectively final.

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
public static void main(String[] args)
{
final int factor = 10;
int num;
Scanner keyboard = new Scanner([Link]);
IntCalculator multiplier= x -> x * factor;
[Link]("Enter a number: ");
num = [Link]();
[Link]("Multiplied by 10, “
+ " that number is " +
[Link](num));

©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

You might also like