Polymorphism

Download Report

Transcript Polymorphism

Chapter 13
Inheritance and Polymorphism
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 13 Objectives
After you have read and studied this
chapter, you should be able to
• Write programs that are easily extensible and
modifiable by applying polymorphism in
program design.
Polymorphism comes from the Greek word
meaning “many forms.”
• Define reusable classes based on inheritance
and abstract classes and abstract methods.
• Define methods, using the protected
modifier.
• Parse strings, using a String Tokenizer
object.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.1
A superclass Student and its subclasses
GraduateStudent and
UndergraduateStudent.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Inheritance and Polymorphism
Two importance and powerful features in object-oriented
programming are:
Inheritance and Polymorphism
1.Inheritance is the mechanism to design
two or more entities that are different but share many
common features
Java interface and inheritance both model an IS-A
relationship (strong relationship):
2. Polymorphism comes from the Greek word
meaning “many forms.”
The principle is that the actual type of the object
determines the method called.
In Java, all instance methods are polymorphic.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
To explain the concept of inheritance,
we will consider an example of a class
roster.
The class roster should contain both
undergraduate and graduate students.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
Each student’s record will contain his or
her name, three test scores, and the
final course grade.
The formula for determining the course
grade is different for graduate
students than for undergraduate
students.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
The formula for determining the course grade is different
for graduate students than for undergraduate students.
Type of Students
Undergraduate
Graduate
Grading Scheme
Pass if (Test1 + Test2 +
test3)/3 >= 70
Pass if (Test1 + Test2 +
test3)/3 >= 80
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
There are two broad ways to design the
classes to model undergraduate and
graduate students.
• We can define two unrelated classes, one
for undergraduates and one for graduates.
• We can model the two kinds of students
by using classes that are related in an
inheritance hierarchy.
Two classes are unrelated if they are
not connected in an inheritance
relationship.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
If two objects are expected to share
common behaviors and data, it is
better to design their classes using
inheritance.
Using unrelated classes in such an
instance will result in duplicating code
common to both classes.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
You can create a subclass from a
superclass by adding new fields and
methods.
You can override the methods in the
superclass.
The keyword this is used to reference
the subclass.
The keyword super is used to reference
the superclass.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
For this example, we will design three
classes:
• Student (superClass)
• UndergraduateStudent (subclass)
• GraduateStudent (subclass)
The Student class will incorporate
behavior and data common to both
UndergraduateStudent and
GraduateStudent objects.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
The UndergraduateStudent class and
the GraduateStudent class will each
contain behaviors (methods) and data
specific to their respective objects.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
/*
File: Student.java superclass
*/
class Student {
protected
protected
protected
protected
final static int NUM_OF_TESTS = 3;
String
name;
int[]
test;
String
courseGrade;
public Student( ) { //default constructor
this("No Name");
}
//non-default constructor
public Student(String studentName) {
name = studentName;
test = new int[NUM_OF_TESTS];
courseGrade = "****";
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
public String getCourseGrade( ) {
return courseGrade;
}
public String getName( ) {
return name;
}
public int getTestScore(int testNumber) {
return test[testNumber-1];
}
public void setName(String newName) {
name = newName;
}
public void setTestScore(int testNumber, int
testScore) {
test[testNumber-1] = testScore;
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
The visibility modifier protected makes
a data member or method visible and
accessible to only the instances of the
class and the descendant(subclass)
classes.
Public data members and methods are
accessible to everyone.
Private data members and methods are
accessible only to instances of the
class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
The UndergraduateStudent and
GraduateStudent classes are descendants of
the Student class.
A subclass extends its superclass.A subclass is a
specialization of its superclass.
Following are the class definitions for the
UndergraduateStudent and GraduateStudent
classes.
A subclass cannot have multiple inheritance
(more than one parent)- can only extend one
superclass.
Can implement many interfaces to achieve
multiple inheritance
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance to
achieve multiple inheritance
Syntax to declare multiple inheritance using interfaces:
Public class Newclass extends Baseclass
implements Interface1, Interface2…N
{
}
Syntax to declare an interface:
modifier interface InterfaceName
{
// constants declarations
// method signatures
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
/*
File: UndergraduateStudent.java subclass
*/
class UndergraduateStudent extends Student {
public void computeCourseGrade() {
int total = 0;
for (int i = 0; i < NUM_OF_TESTS; i++) {
total += test[i];
}
if (total / NUM_OF_TESTS >= 70) {
courseGrade = "Pass";
} else {
courseGrade = "No Pass";
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.1 Defining Classes with Inheritance
/*
File: GraduateStudent.java subclass
*/
class GraduateStudent extends Student {
public void computeCourseGrade() {
int total = 0;
for (int i = 0; i < NUM_OF_TESTS; i++) {
total += test[i];
}
if (total / NUM_OF_TESTS >= 80) {
courseGrade = "Pass";
} else {
courseGrade = "No Pass";
}
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
Polymorphism allows a single variable to refer to
objects from different classes
.
Since GraduateStudents and Undergraduate
Student are enrolled in a class. Should we
declare two arrays?
No. Arrays must contain elements of the same
data type when we store integers and real
numbers.
Not so, when the elements of an array are
objects the objects may be different.
Student[] roster = new Student [40];
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.2 The roster array with elements referring
to instances of GraduateStudent or
UndergraduateStudent classes.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
Polymorphism allows a single variable to
refer to objects from different classes.
Also, polymorphism denotes the principle
that behavior (methods) can vary (be
called) depending on the actual type of
an object.
The actual type of the object determines
the method to be called.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Polymorphism
We can maintain our class roster
using an array, combining objects
from the Student,
UndergraduateStudent, and
GraduateStudent classes.
Student roster [40];
roster[0] = new GraduateStudent();
roster[1] = new UndergraduateStudent();
roster[2] = new UndergraduateStudent();
and so on.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes Effectively with Polymorphism
For example, if we declare
Student student;//The Superclass
We can say
student = new Student();
but also
student = new
GraduateStudent();
or
student = new
UndergraduateStudent();
Note: An object of a subclass can
refer to any object of its
superclass.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
A subclass is a specialization of its superclass, every
instance of a subclass is an instance of its superclass, but
not vice versa.
For example:
Every GraduateStudent is a Student, but every Student is
not a GraduateStudent.
Also, every UndergraduateStudent is a Student but every
Student is not an underGradStudent.
The following assignment statements are invalid:
GraduateStudent grad1;
UndergraduateStudent grad2;
grad1 = new Student(); //superclass
grad2 = new Student(); //superclass
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
We cannot make a variable of a subclass
refer to an object from its sibling classes.
Sibling classes are those that share the common ancestor
class (superclass).
The following assignment statements are invalid
GraduateStudent grad1;
UndergraduateStudent grad2;
grad1 = new UndergraduateStudent(); //sibling class
grad2 = new GraduateStudent(); //sibling class
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
To compute the course grade using the
roster array, we execute
for (int i=0; i<numberOfStudents; i++){
roster[i].computeCourseGrade();
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
If roster[i] refers to a GraduateStudent,
then the computeCourseGrade
method of the GraduateStudent class
is executed.
If roster[i] refers to an
UndergraduateStudent, then the
computeCourseGrade method of the
UndergraduateStudent class is
executed.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
The computeCourseGrade method is called
polymorphic because the message refers to
methods from different classes depending on the
object referenced by roster[i].
Benefits:
Polymorphism allows us to maintain the class
roster with one array instead of maintaining a
separate array for each type of student. This
simplifies the processing tremendously.
Polymorphism, as you can see, permits the
smooth and easy extension and modification of
a program. We can add a third type of student to
the array without rewriting existing code.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
The instanceof operator can help us learn
the class of an object.
Student x = new UndergraduateStudent();
if(x instanceof UndergraduateStudent ){
System.out.println(“Mr. X is an
undergraduate student”);
}else{
System.out.println(“Mr. X is a
graduate student”);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.2 Using Classes
Effectively with Polymorphism
The following code counts the
number of undergraduate students
in the roster array.
int undergradCount= 0;
for(int i = 0; i < numberOfStudents; i++)
{
if roster[i] instanceof UndergraduateStudent)
{
undergradCount++;
} // end if statement
}// end for statement
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
In addition to declaring members
private and public, we can declare
them protected.
The protected modifier is meaningful
only if used with inheritance.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
class Super{
public int public_Super_Field;
protected int protected_Super_Field;
private int private_Super_Field;
//default constructor
public Super(){
public_Super_Field = 10;
protected_Super_Field = 20;
private_Super_Field = 30;
}
...
}
Note: super is a reserved word so don’t use
it.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
class Sub extends Super {
public int public_Sub_Field;
protected int protected_Sub_Field;
private int private_Sub_Field;
//default constructor
public Sub(){
public_Sub_Field = 100;
protected_Sub_Field = 200;
private_Sub_Field = 300;
}
...
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
The protected Modifier, cont.
pacakge p1
class C1
protected int x
class C3
C1 c1;
c1.x can be read or
modified
pacakge p2
class C2 extends C1
x can be read or
modified in C2
class C4
C1 c1;
c1.x cannot be read
nor modified
Note C4 is in a different package and it is
not a subclass
C1.
©TheMcGraw-Hill
Companies, Inc. Permission required for reproduction or display.
Summary of Access Level for Members of a Class
with respect to class inheritance
Modifier
|class |package|subclass|World
____________________________________________
|private
|X
|| ||no modifier |X
|X
| ||protected
|X
|X
|X
||public
|X
|X
|X
|X
No modifier is also known as packageprivate or package visibility.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.3
A graphical representation of superclasses and
subclasses with public, private, and protected
members.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
A public member is accessible to any
method.
A private member is accessible only to
the methods that belong to the same
class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and Member Accessibility
class Client { //Client is unrelated to
// the classes Super and Sub
public void test(){
Super mySuper = new Super();
Sub mySub = new Sub();
int i = mySuper.public_Super_Field;
// inherited by mySub
int j = mySub.public_Super_Field;
int k = mySub.public_Sub_Field;
}
}
The above three statements are valid. Public members of a
class, whether they are inherited or not, are accessible from any
object or class
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
class Client { // an unrelated class
public void test(){
Super mySuper = new Super();
Sub mySub = new Sub();
int l = mySuper.private_Super_Field;
int m = mySub.private_Sub_Field;
int n = mySub.private_Super_Field;
}
}
The above three statements are invalid. Private members of
a class are never accessible from any outside object or
class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
A protected member is accessible only
to the methods that belong to the
same class or to the descendant
classes.
It is inaccessible to the methods of an
unrelated class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.3 Inheritance and
Member Accessibility
class Client {
public void test(){
Super mySuper = new Super();
Sub mySub = new Sub();
int o = mySuper.protected_Super_Field;
int p = mySub.protected_Sub_Field;
int q = mySub.protected_Super_Field;
}
}
The statements above are invalid.
This class is unrelated to the classes Super and
Sub therefore Client cannot accessed their
protected members.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.4
The difference between public, private,
and protected modifiers. Only public
members are visible from outside.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.5
Everything(public and protected)
except the private members of the Super class is
visible from a method of the Sub class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.6
Data members accessible from an
instance (object) are also accessible from
other instances (objects) of the same
class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.4 Inheritance and Constructors
Unlike members of a superclass,
constructors of a superclass are not
inherited by its subclasses.
You must define a constructor for a
class or use the default constructor
added by the compiler.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.4 Inheritance and Constructors
A class definition such as
Class Person {
public void sayHello() {
System.out.println(“Well, hello.”);
}
}
is equivalent to
Class Person {
public Person(){
super();//This statement calls the super
//class constructor
}
public void sayHello() {
System.out.println(“Well, hello.”);
}
}
Note: The compilier will provide a default
constructor if you do not provide any constructor.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.4 Inheritance and Constructors
The statement
super();
calls the superclass’s constructor.
Every class has a super class.
If the class declaration does not
explicitly designate the superclass with
the extends clause, then the class’s
superclass is the Object class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.4 Inheritance and Constructors
If you declare a constructor, then no
default constructor is added to the
class. If you define a class as
class MyClass {
public MyClass(int x){
...
}
}
then a statement
MyClass test = new MyClass();
is invalid because MyClass has no
matching default constructor.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.4 Inheritance and Constructors
If the constructor you define does not
contain an explicit call to a superclass
constructor, then the compiler adds
the statement
super();
as the first statement of the constructor.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Calling Superclass Constructors
C3
C2
C1
See classes C1, c2, and c3 on the M: Drive in the Sample
folder.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.4 Inheritance and Constructors
If a class has a superclass that is not
the Object class, then a constructor of
the class should make an explicit call
to a constructor of the superclass.
Always provide a constructor for every
class you define. Don’t rely on default
constructors.
See class C1 on the M: Drive in the Sample
folder.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
Abstract classes are like regular classes with
data and methods, but you cannot create
instances (objects) of abstract classes using
the new operator.
An abstract method cannot be placed in a
nonabstract class.
If a subclass of an abstract superclass does
not implement all the abstract methods, the
subclass must be declared abstract.
.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
A classes that contains abstract
methods must be abstract. However, it
is possible to declare an abstract class
that contains no abstract methods.
A subclass can be abstract even if its
superclass is concrete.
.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
When we define a superclass, we often
do not need to create any instances of
the superclass.
Depending on whether we need to
create instances (objects) of the
superclass, we must define the class
differently.
We will study examples based on the
Student superclass defined earlier.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
Example Case 1: Student Must Be
Undergraduate or Graduate
If a student must be either an undergraduate
or a graduate student, we only need
instances (objects) of
UndergraduateStudent or
GraduateStudent.
Therefore, we must define the Student
class so that no instances (objects) may
be created of it.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
An abstract class is a class defined with
the modifier abstract. No instances
can be created from an abstract class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
abstract class Student {
protected final static int NUM_OF_TESTS = 3;
protected String name;
protected int[] test;
protected String courseGrade;
public Student() {
this(“No name”);
}
public Student(String studentName){
name = studentName;
test = new int[NUM_OF_TESTS];
courseGrade = “******”;
}
abstract public void computeCourseGrade();
Note: If a subclass of this abstract superclass does not implement this
abstract methods, the subclass must be declared abstract.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
public String getCourseGrade(){
return courseGrade;
}
public String getName(){
return name;
}
public int getTestScore(int testNumber) {
return test[testNumber-1];
}
public void setName(String newName){
name = newName;
}
public void setTestScore(int testNumber, int
testScore){
test[testNumber-1] = testScore;
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
An abstract method is a method with the
keyword abstract, and it ends with a
semicolon instead of a method body.
A class is abstract if the class contains
an abstract method or does not
provide an implementation of an
inherited abstract method.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
We say a method is implemented
(concrete) if it has a method body.
If a subclass has no abstract methods
and no unimplemented inherited
abstract methods, then the subclass is
no longer abstract, and instances
(objects) may be created of it.
An abstract class must contain the
keyword abstract in its definition.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
In a program diagram, we represent an
abstract class by using the keyword
abstract.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
Example Case 2: Student Does Not Have to
Be Undergraduate or Graduate.
In this case, we may design the
Student class in one of two ways.
1. We can make the Student class
instantiable (able to create an object).
OR
2. We can leave the Student class
abstract and add a third subclass,
OtherStudent, to handle a student who
does not fall into the
UndergraduateStudent or
GraduateStudent categories.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
With the second approach, we delete the
keyword abstract from the class and
method definition. We provide a method
body for computeCourseGrade.
class Student {
...
public void computeCourseGrade(){
int total = 0;
for (int i=0; i<NUM_OF_TESTS; i++){
total += test[i];
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
if (total/NUM_OF_TESTS >=50){
courseGrade = “Pass”;
}else{
courseGrade = “No Pass”;
}
}
...
}
This design allows us to create an
instance of Student to represent a
nonregular student.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
In the second approach, we leave the Student
class abstract. We define a third subclass,
OtherStudent (better approach):
class OtherStudent extends Student {
public void computeCourseGrade(){
int total = 0;
for (int i=0; i<NUM_OF_TESTS; i++){
total += test[i];
}
if (total/NUM_OF_TESTS >=50){
courseGrade = “Pass”;
}else{
courseGrade = “No Pass”;
}
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 13.7
A program diagram of the abstract
superclass Student and its three
subclasses.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.5 Abstract Superclasses
and Abstract Methods
The best approach depends on the
particular situation.
When considering design options, we
can ask ourselves which approach
allows easier modification and
extension.
Not all methods can be declared
abstract. Private methods and static
methods can not be declared
abstract.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.6 Inheritance versus Interface
Java interface and inheritance both model
an IS-A relationship:
class ButtonHandler implements
ActionListener
Class SavingsAccount extends Account
We say “ButtonHandler is an
ActionListener” and “SavingsAccount is
an Account.”
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.6 Inheritance versus Interface
However, their uses are very different.
The Java interface is used to share
common behavior (only method headers)
among the instances of different classes.
Inheritance is used to share common code
(including both data members and
methods) among the instances of related
classes.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.6 Inheritance versus Interface
In your program designs, remember to
use the Java interface to share
common behavior. Use inheritance to
share common code.
If an entity A is a specialized form of
another entity B, then model them by
using inheritance. Declare A as a
subclass of B.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.6 Interface
An interface is a classlike construct. It contains
only constants and abstract methods.
An interface is treated like a a special class in
Java. Each interface is compiled into a
separate bytecode file same as a regular
class.
You cannot create an instance (object) from an
interface using the new operator.
The java.lang.Comparable interface defines
the compareTo method. Many classes in the
Java library implement Comparable.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.6 Define an Interface
The data must be constants.
Each method in an interface has only a signature without
implementation.
Syntax:
public interface NewInterface
{
/** Constants declarations */
public static final int CONSTANT_J = 2;
/** Method signatures*/
public abstract void AbstractMethod();
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
13.6 Define an Interface
Java allows only single inheritance for
class extensions. Java allows multiple
extensions for interfaces.
public class SubClassName extends
SuperClass implements Interface1,
… InterfaceN
{}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Interface Comparable
//Interface for comparing objects, defined in java.lang
// The compareTo method determines the order of this
// object with the specified/ object o, and returns a
// negative integer, zero, or a positive integer if this
// object is less than, equal to, or greater than the specified
// object o
package java.lang;
public interface Comparable {
public int compareTo(Object o);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Interface Comparable
// Max.java: Find the maximum object of the
//two objects. Note to use this method, you
// must first implement the Comparable interface for
// the class of these two objects.
public class Max {
/** Return the maximum between two objects */
public static Comparable max(Comparable
o1, Comparable o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Programs to Use
Programs are stored on the M: drive in the
Sample folder:
•
•
•
•
•
•
•
•
•
•
TestEdible
Edible
Animal
Chicken
Tiger
Elephant
Fruit
Apple
Orange
Cherry
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
TestEdible
(Driver)
<<Edible>>
Animal
Elephant
Tiger
Chicken
Fruit
Apple
Cherry
Tiger
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.