0% found this document useful (0 votes)
9 views39 pages

CH13 Abstract Classes and Interfaces

Uploaded by

ahmedhesham43886
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)
9 views39 pages

CH13 Abstract Classes and Interfaces

Uploaded by

ahmedhesham43886
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
You are on page 1/ 39

Chapter 13

Abstract Classes and Interfaces

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 1
Motivations
In order to write such code, you have to know
about interfaces.
An interface is for defining common behavior for
classes (including unrelated classes).
Before discussing interfaces, we introduce a
closely related subject: abstract classes.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 2
Objectives
To design and use abstract classes (§13.2).
To generalize numeric wrapper classes, BigInteger, and BigDecimal
using the abstract Number class (§13.3).
To specify common behavior for objects using interfaces (§13.5).
To define interfaces and define classes that implement interfaces
(§13.5).
To define a natural order using the Comparable interface (§13.6).
To explore the similarities and differences among concrete classes,
abstract classes, and interfaces (§13.8).
To design classes that follow the class-design guidelines (§13.10).

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 3
Abstract Classes and Abstract Methods

Rectangle

TestGeometricObject

Run

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 4
public abstract class GeometricObject {
private String color = "white";
private boolean filled; GeometricObject class
private java.util.Date dateCreated;

protected GeometricObject() {
dateCreated = new java.util.Date(); }
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled; }
public String getColor() { return color; } public String toString() {
public void setColor(String color) { return "created on " + dateCreated +
this.color = color; } "\ncolor: " + color + " and filled: " + filled;
public boolean isFilled() { }
return filled; /** Abstract method getArea */
} public abstract double getArea();
public void setFilled(boolean filled) {
/** Abstract method getPerimeter */
this.filled = filled;
} public abstract double getPerimeter();
public java.util.Date getDateCreated() { }
return dateCreated;
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 5
Circle class
public class Circle extends GeometricObject {
private double radius;
public Circle() { }
public Circle(double radius) { this.radius = radius; }
public double getRadius() { return radius; }
public void setRadius(double radius) { this.radius = radius; }
@Override /** Return area */
public double getArea() { return radius * radius * Math.PI; }
public double getDiameter() { return 2 * radius; }
@Override /** Return perimeter */
public double getPerimeter() { return 2 * radius * Math.PI; }
/* Print the circle info */
public void printCircle() {
System.out.println("The circle is created " + getDateCreated() +
" and the radius is " + radius);
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 6
public class Rectangle extends GeometricObject {
private double width;
private double height;
Rectangle class
public Rectangle() { }
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() { return width; }
public void setWidth(double width) { this.width = width; }
public double getHeight() { return height; }
public void setHeight(double height) { this.height = height; }
@Override /** Return area */
public double getArea() {
return width * height;
}
@Override /** Return perimeter */
public double getPerimeter() {
return 2 * (width + height);
}
} Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 7
public class TestGeometricObject {
/** Main method */
public static void main(String[] args) { TestGeometricObject
// Declare and initialize two geometric objects class
GeometricObject geoObject1 = new Circle(5);
GeometricObject geoObject2 = new Rectangle(5, 3);
System.out.println("The two objects have the same area? " +
equalArea(geoObject1, geoObject2));
displayGeometricObject(geoObject1); // Display circle
displayGeometricObject(geoObject2); // Display rectangle
}
/** A method for comparing the areas of two geometric objects */
public static boolean equalArea(GeometricObject object1, GeometricObject object2) {
return object1.getArea() == object2.getArea();
}
/** A method for displaying a geometric object */
public static void displayGeometricObject(GeometricObject object) {
System.out.println();
System.out.println("The area is " + object.getArea());
System.out.println("The perimeter is " + object.getPerimeter());
}
} Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 8
abstract method in abstract class
An abstract method cannot be contained in a
nonabstract class.
If a subclass of an abstract superclass does not
implement all the abstract methods, the subclass
must be defined abstract.
In other words, in a nonabstract subclass extended
from an abstract class, all the abstract methods must
be implemented, even if they are not used in the
subclass.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 9
object cannot be created from
abstract class
An abstract class cannot be instantiated using
the new operator, but you can still define its
constructors, which are invoked in the
constructors of its subclasses.
For instance, the constructors of
GeometricObject are invoked in the Circle
class and the Rectangle class.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 10
abstract class without abstract
method
A class that contains abstract methods must
be abstract.
However, it is possible to define an abstract
class that contains no abstract methods.
In this case, you cannot create instances of the
class using the new operator.
This class is used as a base class for defining a
new subclass.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 11
superclass of abstract class may be
concrete
A subclass can be abstract even if its
superclass is concrete.
For example, the Object class is concrete, but
its subclasses, such as GeometricObject, may
be abstract.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 12
concrete method overridden to be
abstract
A subclass can override a method from its
superclass to define it abstract.
This is rare, but useful when the implementation of
the method in the superclass becomes invalid in the
subclass.
In this case, the subclass must be defined abstract.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 13
abstract class as type
You cannot create an instance from an abstract class
using the new operator, but an abstract class can be
used as a data type.
GeometricObject ob=new Circle();
Therefore, the following statement, which creates
an array whose elements are of GeometricObject
type, is correct.
GeometricObject[] geo = new GeometricObject[10];

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 14
Interfaces
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 15
What is an interface?
Why is an interface useful?
An interface is a classlike construct that contains only
constants, and
abstract methods.
In many ways, an interface is similar to an abstract class,
but the intent of an interface is to specify common
behavior for objects.
For example, you can specify that the objects are
comparable, edible, cloneable using appropriate interfaces.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 16
Define an Interface
To distinguish an interface from a class, Java uses the
following syntax to define an interface:
public interface InterfaceName {
constant declarations;
abstract method signatures;
}

Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 17
Interface is a Special Class
An interface is treated like a special class in Java. Each
interface is compiled into a separate bytecode file, just like
a regular class.
Like an abstract class, you cannot create an instance from
an interface using the new operator, but in most cases you
can use an interface more or less the same way you use an
abstract class.
For example, you can use an interface as a data type for a
variable, as the result of casting, and so on.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 18
Example
You can now use the Edible interface to specify whether an
object is edible. This is accomplished by letting the class for
the object implement this interface using the implements
keyword. For example, the classes Chicken and Fruit
implement the Edible interface (See TestEdible).

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 19
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
} abstract class Animal {
/** Return animal sound */
public abstract String sound();
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 20
class Tiger extends Animal {
@Override
public String sound() {
return "Tiger: RROOAARR";
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 21
class Chicken extends Animal implements Edible {
@Override
public String howToEat() {
return "Chicken: Fry it";
}
@Override
public String sound() {
return "Chicken: cock-a-doodle-doo";
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 22
abstract class Fruit implements Edible {
// Data fields, constructors, and methods omitted here
// but the method howToEat() still abstract
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 23
class Apple extends Fruit {
@Override
public String howToEat() {
return "Apple: Make apple cider";
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 24
class Orange extends Fruit {
@Override
public String howToEat() {
return "Orange: Make orange juice";
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 25
TestEdible class
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new Apple()};
for (int i = 0; i < objects.length; i++) {
if (objects[i] instanceof Edible)
System.out.println(((Edible)objects[i]).howToEat());

if (objects[i] instanceof Animal) {


System.out.println(((Animal)objects[i]).sound());
}
}
Output
} Tiger: RROOAARR
} Chicken: Fry it
Chicken: cock-a-doodle-doo
Apple: Make apple cider
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 26
Omitting Modifiers in Interfaces
All data fields are public final static
All methods are public abstract in an interface.
For this reason, these modifiers can be omitted, as shown
below:
public interface T1 { public interface T1 {
public static final int K = 1; Equivalent int K = 1;

public abstract void p(); void p();


} }

A constant defined in an interface can be accessed using syntax


InterfaceName.CONSTANT_NAME (e.g., T1.K).

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 27
Example: The Comparable Interface

// This interface is defined in


// java.lang package
package java.lang;

public interface Comparable<E> {


public int compareTo(E o);
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 28
The toString, equals, and hashCode
Methods
Each wrapper class overrides the toString, equals,
and hashCode methods defined in the Object class.
Since all the numeric wrapper classes and the
Character class implement the Comparable
interface, the compareTo method is implemented
in these classes.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 29
Integer and BigInteger Classes
public class Integer extends Number public class BigInteger extends Number
implements Comparable<Integer> { implements Comparable<BigInteger> {
// class body omitted // class body omitted

@Override @Override
public int compareTo(Integer o) { public int compareTo(BigInteger o) {
// Implementation omitted // Implementation omitted
} }
} }

String and Date Classes


public class String extends Object public class Date extends Object
implements Comparable<String> { implements Comparable<Date> {
// class body omitted // class body omitted

@Override @Override
public int compareTo(String o) { public int compareTo(Date o) {
// Implementation omitted // Implementation omitted
} }
} }

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 30
Example
1 System.out.println(new Integer(3).compareTo(new Integer(5)));
2 System.out.println("ABC".compareTo("ABE"));
3 java.util.Date date1 = new java.util.Date(2013, 1, 1);
4 java.util.Date date2 = new java.util.Date(2012, 1, 1);
5 System.out.println(date1.compareTo(date2));

Output
-1
-2
1

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 31
Generic sort Method
Let n be an Integer object,
s be a String object,
and d be a Date object.
All the following expressions are true.
n instanceof Integer s instanceof String d instanceof java.util.Date
n instanceof Object s instanceof Object d instanceof Object
n instanceof Comparable s instanceof Comparable d instanceof Comparable

The java.util.Arrays.sort(array) method requires that


the elements in an array are instances of
Comparable<E>.
SortComparableObjects Run

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 32
import java.math.BigInteger;

public class SortComparableObjects {


public static void main(String[] args) {
String[] cities = {"Savannah", "Boston", "Atlanta", "Tampa"};
java.util.Arrays.sort(cities);
for (String city: cities)
System.out.print(city + " ");
System.out.println();

BigInteger[] hugeNumbers = {new BigInteger("2323231092923992"),


new BigInteger("432232323239292"), new BigInteger("54623239292")};
java.util.Arrays.sort(hugeNumbers);
for (BigInteger number: hugeNumbers)
System.out.print(number + " ");
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 33
Defining Classes to Implement Comparable

The classes GeometricObject are Rectangle codes written


before at slides number 5 and 7

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 34
class ComparableRectangle extends Rectangle implements Comparable<ComparableRectangle> {
/** Construct a ComparableRectangle with specified properties */
public ComparableRectangle(double width, double height) {
super(width, height);
}
@Override // Implement the compareTo method defined in Comparable
public int compareTo(ComparableRectangle o) {
if (getArea() > o.getArea())
return 1;
else if (getArea() < o.getArea())
return -1;
else
return 0;
}
@Override // Implement the toString method in GeometricObject
public String toString() {
return "Width: " + getWidth() + " Height: " + getHeight() +
" Area: " + getArea();
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 35
public class SortRectangles {
public static void main(String[] args) {
ComparableRectangle[] rectangles = {
new ComparableRectangle(3.4, 5.4),
new ComparableRectangle(13.24, 55.4),
new ComparableRectangle(7.4, 35.4),
new ComparableRectangle(1.4, 25.4)
};
java.util.Arrays.sort(rectangles);
for (Rectangle rectangle: rectangles) {
System.out.print(rectangle + " ");
System.out.println();
}
}
}

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 36
Interfaces vs. Abstract Classes
In an interface, the data must be constants; an abstract class can
have all types of data.
Each method in an interface has only a signature without
implementation; an abstract class can have concrete methods.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 37
Interfaces vs. Abstract Classes, cont.
All classes share a single root, the Object class, but there is no single root for
interfaces.
Like a class, an interface also defines a type.
A variable of an interface type can reference any instance of the class that
implements the interface.
If a class extends an interface, this interface plays the same role as a superclass.
You can use an interface as a data type and cast a variable of an interface type to its
subclass, and vice versa.

Suppose that c is an instance of Class2. c is also an instance of Object, Class1,


Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 38
Whether to use an interface or a class?
Abstract classes and interfaces can both be used to model common
features.
How do you decide whether to use an interface or a class?
In general, a strong is-a relationship that clearly describes a parent-child
relationship should be modeled using classes.
For example, a staff member is a person.
A weak is-a relationship, also known as an is-kind-of relationship, indicates
that an object possesses a certain property.
A weak is-a relationship can be modeled using interfaces.
For example, all strings are comparable, so the String class implements the Comparable
interface.
You can also use interfaces to circumvent single inheritance restriction if multiple
inheritance is desired.
In the case of multiple inheritance, you have to design one as a superclass, and
others as interface.

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 39

You might also like