13 Slide
13 Slide
Lecture 10
Abstract Classes & Interfaces (1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Chapter 13 Abstract Classes and Interfaces
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Motivations
We have learned how to write simple programs to create and
display GUI components. Can we write the code to respond
to user actions, such as clicking a button to perform an
action?
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
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 process a calendar using the Calendar and GregorianCalendar
classes (§13.4).
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 make objects cloneable using the Cloneable interface (§13.7).
To explore the similarities and differences among concrete classes,
abstract classes, and interfaces (§13.8).
To design the Rational class for processing rational numbers (§13.9).
To design classes that follow the class-design guidelines (§13.10).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Abstract Classes & Abstract Methods
An abstract class is a class that is declared abstract
GeometricObject
Circle
Rectangle
TestGeometricObject
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6Run
Abstract Classes & Abstract Methods
In a concrete 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, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Abstract Classes
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, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Case Study: Abstract Number Class
LargestNumbers Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Abstract Calendar Class & its Concrete
GregorianCalendar Subclass
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Abstract Calendar Class & its Concrete
GregorianCalendar Subclass
An instance of java.util.Date represents a specific instant in
time with millisecond precision
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
The GregorianCalendar Concrete Class
We can use new GregorianCalendar() to construct a
default GregorianCalendar object with the current time
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
get() in Calendar Class
get(int field) is used to extract detailed information
from Calendar objects. The possible fields are:
TestCalendar
Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Interfaces
The Apple & Chicken classes are based on different
superclasses, but both share a common behavior: both
are edible! We can model this common behavior using
an interface
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
interface & class Similarities
An interface is treated like a special class in Java
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Defining an interface
An interface is a class-like construct that
contains only constants and abstract methods
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
interface inheritance
We can use the Edible interface to specify whether an object is edible.
This is accomplished by letting the class for the object implement this
interface (or inherit the interface) using the implements keyword
Example: Chicken & Fruit implement the Edible interface in
TestEdible
package java.lang;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
compareTo() in Integer, BigInteger, String & Date
All numeric wrapper classes, Character and String implement
Comparable, thus compareTo() is implemented in all of them
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
} }
} }
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, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
Example: compareTo()
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
The Comparable Interface
Let n be an Integer object, s be a String object and d be
a Date object. Then, all the following expressions are true
n instanceof Integer
n instanceof Object
n instanceof Comparable
s instanceof String
s instanceof Object
s instanceof Comparable
d instanceof java.util.Date
d instanceof Object
d instanceof Comparable
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
CS 112 Programming 2
Lecture 11
Abstract Classes & Interfaces (2)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
First Midterm Exam
• Monday, 29 February (same time as the lecture)
• 75 minute duration
• If you miss this exam for any reason, you will have to appear
for a makeup exam on the Thursday of the last week of
teaching (5 May). That exam will cover all lectures delivered
in the semester. It will consist of programming tasks, drawing
of diagrams and answering questions having 0.5-1 page
answers
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Generic sort()
java.util.Arrays.sort(array) requires
that the elements in an array implement the
Comparable<E> interface
SortComparableObjects Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
Defining Classes to Implement Comparable
We cannot use sort() to sort an array of Rectangle objects,
because Rectangle does not implement Comparable
However, we can define a new rectangle class that implements
Comparable. The instances of this new class are comparable
package java.lang;
public interface Cloneable {
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
Example: Cloneable
Several classes (e.g., Date, Calendar and ArrayList) in the Java
library implement Cloneable. Thus, the instances of these classes
can be cloned. For example, the following code:
displays
calendar == calendarCopy is false
calendar.equals(calendarCopy) is true
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
Implementing Cloneable Interface
To define a custom class that implements the Cloneable
interface, the class must override clone() in Object
House
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
Shallow vs. Deep Copy
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
If object A is copied
as object B then if any
properties of A are a
reference to a
memory location, at
the end of copying the
two objects will be
using the same
reference. The default
clone() makes a
shallow copy
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
Shallow vs. Deep Copy
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
Instead of references,
if the actual values
are copied to a new
object then that will
be a deep copy. This
way the two objects
are completely
independent. To make
a deep copy, we need
to override the default
clone()
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
Interfaces vs. Abstract Classes
Variables Constructors Methods
Constructors are invoked
by subclasses through
No restrictions
Abstract No constructor chaining. An
(abstract methods
class restrictions abstract class cannot be
can’t be static)
instantiated using the new
operator
Must be No constructors. An Must be public
public interface cannot be abstract
Interface static
instantiated using the new (abstract methods
final operator can’t be static)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
Interfaces
All classes share a single root (Object). There is no single root for interfaces
A variable of an interface type can reference any instance of the class that
implements that interface
Sub-interfaces: public interface infB extends infA {…}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
Class Design Guidelines: Consistency
Follow standard Java programming style and naming conventions
– Choose informative names for classes, data fields, and methods
– Place the data declaration before the constructor and place
constructors before methods
– Make the names consistent. For example, length() returns the size
of a String, StringBuilder, or StringBuffer. It would not be
consistent if different names were used for this method in these classes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 37
Class Design Guidelines: Clarity
Cohesion, consistency, & encapsulation improve class clarity. A class
should also have a clear contract that is easy to explain & understand
Users should be able to use classes in many different combinations,
orders, and environments. Therefore, design a class that
– imposes no restrictions on how or when the user can use it
– allows the user to set properties in any order and with any
combination of values
– executes methods correctly independent of their order of occurrence
Methods should be defined intuitively without causing confusion
– Example: It is more intuitive to return a substring from beginIndex
to endIndex, instead of beginIndex to endIndex-1)
Do not declare a data field that can be derived from other data
fields (e.g. no need to store both birthdate and age)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
Class Design Guidelines: Completeness
Classes are designed for use by many different customers. In
order to be useful in a wide range of applications, a class should
provide a variety of ways for customization through properties
and methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 39
Class Design Guidelines: Instance vs. static
A variable or method that is dependent on a specific instance of the
class must be an instance variable or method
A variable that is shared by all the instances of a class should be
declared static
A method that is not dependent on a specific instance should be
defined as a static method
Always reference static variables and methods from a class
name to improve readability and avoid errors
A static variable or method can be invoked from an instance
method, but an instance variable or method cannot be invoked from
a static method
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 40
Class Design Guidelines: Inheritance vs. Aggregation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 41
Class Design Guidelines: Interfaces vs. Abstract Classes
Both can be used to specify common behavior. In general, a strong
is-a relationship that clearly describes a parent-child relationship
should be modeled using classes, e.g. orange is a fruit
A weak is-a (or is-kind-of ) relationship, indicates that an object
possesses a certain property. A weak is-a relationship can be
modeled using interfaces, e.g. all strings are comparable, so the
String class implements the Comparable interface
A circle or a rectangle is a geometric object, so Circle can be
designed as a subclass of GeometricObject. Circles are different
and comparable based on their radii, so Circle can implement the
Comparable interface
A subclass can extend only one superclass but can implement any
number of interfaces
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Class Design Guidelines: Visibility Modifiers
Each class can present two contracts – one for the users of the
class and one for the extenders of the class
The contract for the extenders includes the contract for the users