Lecture 6
Abstract and Interface
Lecture outcomes
• Abstract Classes
• Abstract class & abstract method
• Interfaces
• The Comparable Interface
• Interface vs. Abstract Classes
2
Abstract Classes
• An abstract class can contain abstract methods, which are implemented in concrete subclasses.
• An abstract class cannot be used to create objects.
• In the inheritance hierarchy,
• Classes become more specific and concrete with each new subclass.
• If you move from a subclass back up to a superclass, the classes become more general and less
specific.
• Class design should ensure that a superclass contains common features of its subclasses.
• A superclass is so abstract that it cannot be used to create any specific instances.
• Such a class is referred to as an abstract class.
3
Abstract
Classes
&
Abstract
Methods
4
Abstract Classes & Abstract Methods
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date
dateCreated;
............
/** Abstract
public method
abstract getArea
double */
getArea();
/** Abstract method getPerimeter */
public abstract double getPerimeter();
} 5
Abstract Classes & Abstract Methods
• 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.
• A nonabstract subclass extended from an abstract class, all the abstract
methods must be implemented, even if they are not used
in the subclass.
6
Abstract Classes
• 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.
7
Example
public class TestClass {
public static void main(String[] args) {
// Create two geometric objects
GeometricObject Object1 = new Circle(5);
GeometricObject Object2 = new Rectangle(5, 3);
// Display objects
displayGeometricObject(Object1);
displayGeometricObject(Object2);
}
/** 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());
}
} 8
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.
9
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.
10
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.
11
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[] objects = new GeometricObject[10];
• You can then create an instance of GeometricObject and assign its reference to the array
like this:
objects[0] = new Circle();
12
Case Study: the Abstract Number Class
• The Number class is an
abstract superclass for
Double, Float, Long, Integer,
Short, Byte, BigInteger and
BigDecimal.
13
import java.util.ArrayList;
import java.math.*;
public class LargestNumbers { Example
public static void main(String[] args)
{ ArrayList<Number> list = new ArrayList<>();
list.add(45); // Add an integer
list.add(3445.53); // Add a
double
// Add a BigInteger
list.add(new
BigInteger("3432323234344343101"))
;
// Add a BigDecimal
} list.add(new BigDecimal("2.0909090989091343433344343"));
public static Number getLargestNumber(ArrayList<Number>
System.out.println("The largest number is " + list) {
if (list == null || list.size() ==
getLargestNumber(list));
0) return null;
Number number = list.get(0);
for (int i = 1; i < list.size(); i++)
if (number.doubleValue() < list.get(i).doubleValue())
number = list.get(i);
return number;
14
}
Interfaces
What is an interface?
Why is an interface useful?
How to define an interface?
How do you use an interface?
15
Interfaces
• An interface is containing only constants and Syntax:
abstract methods. Access_modifier interface InterfaceName{
• In many ways, an interface is similar to an /** Constant declarations */
abstract class,
/** Abstract method signatures */
• The intent of an interface is to specify
}
common behavior for objects.
• For example, you can specify that the objects Example:
are comparable, edible, cloneable public interface Edible {
using appropriate interfaces. /** Describe how to eat */
public abstract String howToEat();
16
Interface is a Special Class
• An interface is treated like a special class in Java.
• Like an abstract class, you cannot create an instance from an interface using
the new operator,
• 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.
17
Example
• The Edible interface is used 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
18
Example
abstract class Animal {
/** Return animal sound */
abstract class Fruit implements Edible {
public abstract String sound();
// Data fields, constructors, and methods
} omitted here
class Chicken extends Animal implements Edible { }
@Override
public String howToEat() { class Apple extends Fruit {
@Override
return "Chicken: Fry it";
public String howToEat() {
} return "Apple: Make
@Override apple cider";
public String sound() { }
return "Chicken: AOOAOOO"; }
class Orange extends Fruit {
}
@Override
} public String howToEat() {
class Tiger extends Animal { return "Orange: Make
@Override orange juice";
public String sound() { }
}
return "Tiger:
RROOAARR";
}
} 19
Example
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()
);
}
}
} 20
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
public interface T1 { public interface T1 {
public static final int K = 1; Equivalent int K = 1;
public abstract void p(); void p();
} }
21
The Comparable Interface
• The Comparable interface defines the
compareTo method for comparing objects.
public interface Comparable<E> {
• The interface is defined in java.lang
public int compareTo(E o);
package. }
22
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 • The compareTo
public int compareTo(Integer o) { public int compareTo(BigInteger o) {
// Implementation omitted method
// Implementation omitted determines the
} }
} } order
specified of object
this object
o and
returns a negativewith
integer,
String and Date Classes zero, or athe
positive integer
public class String extends Object public class Date extends Object
implements Comparable<String> { implements Comparable<Date> {
if this object is less than,
// class body omitted // class body omitted
equal to, orgreater than o
@Override @Override
public int compareTo(String o) { public int compareTo(Date o) {
// Implementation omitted // Implementation omitted
} }
} }
23
The Comparable Interface
• Thus, numbers are comparable, strings are comparable, and so are dates. You can use the
compareTo method to compare two numbers, two strings, and two dates.
• For example, the following code:
System.out.println(new Integer(3).compareTo(new Integer(5)));
System.out.println("ABC".compareTo("ABE"));
java.util.Date date1 = new java.util.Date(2013, 1, 1);
java.util.Date date2 = new java.util.Date(2012, 1, 1);
System.out.println(date1.compareTo(date2));
• Displays
-1
-2
1
24
Generic sort Method
import java.math.*;
public class SortComparableObjects {
public static void main(String[] args) {
String[] cities = {"Savannah", "Boston", "Atlanta", "Tampa"};
java.util.Arrays.sort(cities); The java.util.Arrays.sort
for (String city: cities)
System.out.print(city + " "); (array) method requires
System.out.println();
that the elements in an
BigInteger[] hugeNumbers = {new BigInteger("2323231092923992"),
new BigInteger("432232323239292"),array are instances of
new BigInteger("54623239292")};
java.util.Arrays.sort(hugeNumbers);
Comparable<E>.
for (BigInteger number: hugeNumbers)
System.out.print(number + " ");
}
25
}
Defining Classes to Implement
Comparable
• You cannot use the sort method to sort an array of Rectangle objects, because Rectangle
does not implement Comparable.
• However, you can define a new rectangle class that implements Comparable.
• The instances of this new class are comparable.
26
Defining Classes to Implement
Comparable
public 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 super.toString() + " Area: " + getArea();
}
}` 28
Defining Classes to Implement
Comparable
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 + "
} "); 29
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.
29
Assignment
• Design a Triangle class that extends the abstract GeometricObject class. Draw the UML diagram
for the classes Triangle and GeometricObject and then implement the Triangle class.
• Write a test program that prompts the user to enter three sides of the triangle, a color, and a
Boolean value to indicate whether the triangle is filled.
• The program should create a Triangle object with these sides and set the color and filled
properties using the input.
• The program should display the area, perimeter, color, and true or false to indicate whether it
is filled or not.
• Make the class comparable on the basis of the area.
30