Specialized Classes in Inheritance
Specialized Classes in Inheritance
Inheritance
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-2
What is Inheritance?
Generalization vs. Specialization
©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
©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.
©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.
©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.
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);
}
}
©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);
©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
©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);
©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);
}
}
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.
©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
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-38
Chains of Inheritance
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;
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.
©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;
©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);
©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]());
©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);
©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;
©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 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);
©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.
©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:
©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.
• 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);
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 10-68
Interfaces in UML
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.
©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");
©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;
• 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 ;
©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.