Chapter Five
Abstract Classes and Interfaces
Faculty Of Computing,
Bahir Dar Institute of Technology,
Bahir Dar University
1
Objectives
• To design and use abstract classes.
• To specify common behavior for objects using interfaces.
• To define interfaces and define classes that implement interfaces.
• To define a natural order using the Comparable interface.
• To make objects cloneable using the Cloneable interface.
• To explore the similarities and differences among concrete classes,
abstract classes, and interfaces.
2
Abstract Classes and Abstract Methods
• An abstract class can contain abstract methods, which are
implemented in concrete subclasses.
• In previous section, we have defined the superclass GeometricObject
for subclasses Circle and Rectangle.
• GeometricObject models common features of geometric objects.
• Both Circle and Rectangle contain the getArea() and getPerimeter()
methods for computing the area and perimeter of a circle and a
rectangle.
• Since you can compute areas and perimeters for all geometric objects,
it is better to define the getArea() and getPerimeter() methods in the
GeometricObject class.
• However, these methods cannot be implemented in the
GeometricObject class, because their implementation depends on the
3
specific type of geometric object.
Abstract Classes and Abstract Methods
• Such methods are referred to as abstract methods.
• After you define the methods in
GeometricObject, it becomes an abstract class.
• Abstract classes are denoted using the abstract
modifier in the class header.
• In UML graphic notation, the names of abstract
classes and their abstract methods are italicized, as
shown in the following Figure.
4
Abstract Classes and Abstract Methods
5
Abstract Classes and Abstract Methods
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private [Link] dateCreated;
/** Construct a default geometric object */
protected GeometricObject() {
dateCreated = new [Link]();
}
/** Construct a geometric object with color and filled
value */
protected GeometricObject(String color, boolean filled) {
dateCreated = new [Link]();
[Link] = color;
[Link] = filled;
}
/** Return color */
public String getColor() {return color; }
/** Set a new color */
public void setColor(String color) {
[Link] = color;
} 6
Abstract Classes and Abstract Methods
/** Return filled.*/
public boolean isFilled() {
return filled;
}
/** Set a new filled */
public void setFilled(boolean filled) {
[Link] = filled;
}
/** Get dateCreated */
public [Link] getDateCreated() {
return dateCreated;
}
@Override
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
/** Abstract method getArea */
public abstract double getArea();
/** Abstract method getPerimeter */
public abstract double getPerimeter();
7
}
Abstract Classes and Abstract Methods
• Abstract classes are like regular classes, but you cannot create
instances of abstract classes using the new operator.
• An abstract method is defined without implementation. Its
implementation is provided by the subclasses.
• A class that contains abstract methods must be defined as
abstract.
• The constructor in the abstract class is defined as protected,
because it is used only by subclasses.
• When you create an instance of a concrete subclass, its
superclass’s constructor is invoked to initialize data fields
8
defined in the superclass.
Abstract Classes and Abstract Methods
• The GeometricObject abstract class defines the
common features (data fields and methods) for
geometric objects and provides appropriate
constructors.
• Because you don’t know how to compute areas and
perimeters of geometric objects, getArea and
getPerimeter are defined as abstract methods.
• These methods are implemented in the subclasses.
• The implementation of Circle and Rectangle is
shown in the following code. 9
Abstract Classes and Abstract Methods
public class Circle extends GeometricObject {
// Same as the circle class we have
discussed in inheritance section
}
public class Rectangle extends GeometricObject {
//Same as the rectangle class we have
discussed in inheritance section
}
10
Abstract Method in Abstract Class
An abstract method cannot be contained in a non-
abstract 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 non-abstract subclass extended
from an abstract class, all the abstract methods must
be implemented, even if they are not used in the
subclass.
11
Object cannot be created from abstract class
An abstract class cannot be used to create
objects.
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. 12
Abstract class without abstract method
A class that contains abstract methods must
be abstract class.
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.
13
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.
14
concrete method overridden to be abstract
A subclass can override a method from its
superclass to define it as 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.
15
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.
Therefore, the following statement, which creates an array
whose elements are of GeometricObject type, is correct.
GeometricObject[] geo = new GeometricObject[10];
So, you can then create an instance of GeometricObject
and assign its reference to the array like this:
geo[0] = new Circle();
16
What is an Interfaces?
• A superclass defines common behavior for related subclasses.
• An interface can be used to define common behavior for
related and unrelated classes.
• An interface is a class-like construct that contains only
constants and abstract methods.
• In many ways an interface is similar to an abstract class, but
its intent is to specify common behavior for objects of related
classes or unrelated classes.
• For example, you can specify that the objects are
comparable, edible, cloneable using appropriate interfaces.17
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();
}
18
Interfaces 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 reference variable, as the result of casting and so
on. 19
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).
Notation:
«interface» Animal
The interface name and the Edible
method names are italicized. +howToEat(): String
+sound(): String
The dashed lines and hollow
triangles are used to point to
the interface.
Fruit Chicken Tiger
- - -
Orange Apple
- -
20
Example
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new
Apple()};
for (int i = 0; i < [Link]; i++) {
if (objects[i] instanceof Edible)
[Link](((Edible)objects[i]).howToEat());
if (objects[i] instanceof Animal) {
[Link](((Animal)objects[i]).sound());
}
}
}
}
21
Interfaces
abstract class Animal {
/** Return animal sound */
public abstract String sound();
}
class Chicken extends Animal implements Edible {
@Override
public String howToEat() {
return "Chicken: Fry it";
}
@Override
public String sound() {
return "Chicken: cock-a-doodle-doo";
}
} 22
Interfaces
class Tiger extends Animal {
@Override
public String sound() {
return "Tiger: RROOAARR";
}
}
abstract class Fruit implements Edible {
// Data fields, constructors, and methods omitted here
}
class Apple extends Fruit {
@Override
public String howToEat() {
return "Apple: Make apple cider";
}
}
class Orange extends Fruit {
@Override
public String howToEat() {
return "Orange: Make orange juice";
}
23
}
Interfaces
• The Animal class defines the sound() method.
• It is an abstract method and will be implemented by a concrete
animal class.
• The Chicken class implements Edible to specify that chickens
are edible.
• When a class implements an interface, it implements all the
methods defined in the interface with the exact signature and
return type.
• The Chicken class implements the howToEat() method.
• Chicken also extends Animal to implement the sound method.
24
Interfaces
• The Fruit class implements Edible.
• Since it does not implement the howToEat()
method, Fruit must be defined as abstract.
• The concrete subclasses of Fruit must implement
the howToEat() method.
• The Apple and Orange classes implement the
howToEat() method .
25
Interfaces
• The main method creates an array with three
objects for Tiger, Chicken, and Apple, and
invokes the howToEat() method if the element is
edible and the sound() method if the element is an
animal.
• In essence, the Edible interface defines common
behavior for edible objects.
• All edible objects have the howToEat() method.
26
Omitting Modifiers in Interfaces
All data fields are public final static and 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).
It is a good practice to define common constants that are shared
by many classes in an interface.
27
Interfaces vs. Abstract Classes
A class can implement multiple interfaces, but it can only extend one superclass.
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.
Variables Constructors Methods
Abstract No restrictions Constructors are invoked by subclasses No restrictions.
class through constructor chaining. An abstract
class cannot be instantiated using the new
operator.
Interface All variables must No constructors. An interface cannot be All methods must be
be public static instantiated using the new operator. public abstract
final instance methods
28
Interfaces vs. Abstract Classes
• Java allows only single inheritance for class extension but allows multiple extensions
for interfaces. For example,
public class NewClass extends BaseClass implements Interface1, . . ., InterfaceN {
...
}
• An interface can inherit other interfaces using the extends keyword. Such an interface is
called a subinterface. For example, NewInterface in the following code is a
subinterface of Interface1, . . . , and InterfaceN.
public interface NewInterface extends Interface1, . . . , InterfaceN {
// constants and abstract methods
}
• A class implementing NewInterface must implement the abstract methods defined in
NewInterface, Interface1, . . . , and InterfaceN. An interface can extend other
interfaces but not classes. A class can extend its superclass and implement multiple
29
interfaces.
Interfaces vs. Abstract Classes
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
implements 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.
Interface1_2 Interface2_2
Interface1_1 Interface1 Interface2_1
Object Class1 Class2
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.
30
Reading Assignment
• The Comparable Interface
• The Cloneable Interface
31
Inner Classes
• An inner class, or nested class, is a class defined within the
scope of another class.
• Inner classes are useful for defining listener classes.
• Example: See the two classes in the following figure.
• The code in Figure (a) defines two separate classes, Test and
A.
• The code in Figure (b) defines A as an inner class in Test.
• The class InnerClass defined inside OuterClass in Figure
(c) is another example of an inner class. 32
Inner Classes
33
Inner Classes
• Normally, you define a class as an inner class if it
is used only by its outer class.
• An inner class has the following features:
– An inner class is compiled into a class named
OuterClassName$[Link].
– For example, Test$[Link] in the above Figure (b).
– An inner class can reference the data and methods
defined in the outer class in which it nests, so you need
not pass the reference of an object of the outer class to
the constructor of the inner class.
– For this reason, inner classes can make programs
simple and concise.
34
Inner Classes
– An inner class can be defined with a visibility modifier
subject to the same visibility rules applied to a member
of the class.
– An inner class can be defined as static.
– A static inner class can be accessed using the outer class
name.
– A static inner class cannot access non-static members of
the outer class.
– Objects of an inner class are often created in the outer
class. But you can also create an object of an inner class
from another class. 35
Inner Classes
– If the inner class is nonstatic, you must first create an
instance of the outer class, then use the following
syntax to create an object for the inner class:
[Link] innerObject = outerObject. new InnerClass();
– If the inner class is static, use the following syntax to
create an object for it:
[Link] innerObject = new [Link]();
36
The End!!
37