You are on page 1of 38

Abstract Class

&
Interface
Instructor: Wenjia Li
01/08/16

Still Remember
Inheritance?

01/08/16

samePay Method
Suppose that we decide that it will often be
necessary to determine if two Employees have
the same pay.
We decide to implement a method named samePay in
the Employee class.
This method should be able to compare the pays for any
kinds of Employees.

01/08/16

Problem with samePay


The method samePay calls getPay.
While getPay is defined for SalariedEmployees and
HourlyEmployees, there is no meaningful
implementation of getPay for a generic Employee.
We cant implement getPay without knowing the
type of Employee.

Solution:
Require that classes derived from Employee (who know
what type they are) implement a suitable getPay
method that can then be used from samePay.
Java provides this capability through the use of abstract
methods.
01/08/16

Abstract Method Abstract


Class

An abstract method is like a placeholder for a


method that will be fully defined in a descendent class.
It postpones the definition of a method.
It has a complete method heading to which the modifier
abstract has been added.
It cannot be private.
It has no method body, and ends with a semicolon in place of
its body.

The body of the method is defined in the derived classes.

The class that contains an abstract method is called an


abstract class.
01/08/16

Abstract Class
If a class has at least one abstract method,
it must be declared as an abstract class.
Note that a class that has NO abstract
methods may also be declared as abstract, if
desired. For example, a class that contains only
instance variables.)

An abstract class must have the modifier


abstract included in its class heading.

01/08/16

Abstract Class V.S. Concrete


Class
An abstract class can have any number of
abstract and/or fully defined methods.
If a derived class of an abstract class adds to
or does not define all of the abstract methods,
it is abstract also, and
must add abstract to its modifier AS WELL.

A class that is not abstract is called a


concrete class.
01/08/16

Abstract Employee Class

01/08/16

Pitfall: You Cannot Create


Instances of an Abstract Class
An abstract class can only be used to
derive more specialized classes.
While it may be useful to discuss employees in
general, in reality an employee must be a
salaried worker or an hourly worker.

An abstract class constructor cannot be


used to create an object of the abstract
class.
However, a derived class constructor will
include an invocation of the abstract class
constructor in the form of super.
01/08/16

An Abstract Class Is a Type


Although an object of an abstract class
cannot be created, it is perfectly fine to
have a parameter of an abstract class type.
This makes it possible to plug in an object of
any of its descendent classes.

It is also fine to use a variable of an


abstract class type, as long is it names
objects of its concrete descendent classes
only.
01/08/16

10

More Example: Calendar


java.util.Calendar
#Calendar()

Constructs a default calendar.

+get(field: int): int

Returns the value of the given calendar field.

+set(field: int, value: int): void

Sets the given calendar to the specified value.

+set(year: int, month: int,


dayOfMonth: int): void

Sets the calendar with the specified year, month, and date. The month
parameter is 0-based, that is, 0 is for January.

+getActualMaximum(field: int): int

Returns the maximum value that the specified calendar field could have.

+add(field: int, amount: int): void

Adds or subtracts the specified amount of time to the given calendar field.

+getTime(): java.util.Date

Returns a Date object representing this calendars time value (million


second offset from the Unix epoch).

+setTime(date: java.util.Date): void

Sets this calendars time with the given Date object.

java.util.GregorianCalendar
+GregorianCalendar()

Constructs a GregorianCalendar for the current time.

+GregorianCalendar(year: int,
month: int, dayOfMonth: int)

Constructs a GregorianCalendar for the specified year, month, and day of


month.

+GregorianCalendar(year: int,
Constructs a GregorianCalendar for the specified year, month, day of
month: int, dayOfMonth: int,
month, hour, minute, and second. The month parameter is 0-based, that
hour:int, minute: int, second: int)
is, 0 is for January.
01/08/16

11

Calendar Class
An instance of java.util.Date represents a
specific instant in time with millisecond precision.
java.util.Calendar is an abstract base class for
extracting detailed information such as year,
month, date, hour, minute and second from a
Date object.
Subclasses of Calendar can implement specific
calendar systems such as Gregorian calendar,
Lunar Calendar and Jewish calendar.
Currently, java.util.GregorianCalendar for the
Gregorian calendar is supported in the Java API.

01/08/16

12

The GregorianCalendar
Class
Use new GregorianCalendar() to
construct a default GregorianCalendar with
the current time
Use new GregorianCalendar(year,
month, date) to construct a
GregorianCalendar with the specified year,
month, and date. The month parameter is
0-based, i.e., 0 is for January.
01/08/16

13

The get Method in Calendar


Class
The get(int field) method defined in the Calendar class is useful
to extract the date and time information from a Calendar object

01/08/16

14

Interfaces

What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?

01/08/16

15

What is an interface?
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 behavior for objects.
For example, you can specify that the objects
are comparable, edible, cloneable using
appropriate interfaces.

01/08/16

16

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 static final int K = 1;
public abstract void p();
}

Equivalent

public interface T1 {
int K = 1;
}

void p();

A constant defined in an interface can be accessed


using syntax InterfaceName.CONSTANT_NAME
(e.g., T1.K).
01/08/16

17

Public Interface
Objects define their interaction with
the outside world through the their
public interface
A class' public interface is the set of
public members that a user can access
Public non-static members & methods
Public static members & methods
01/08/16

18

Java Interface
Interfaces in Java are a set of behaviors
that are common to multiple classes.
The implementation of an Interface is
similar to a class, except that interfaces:
Use the keyword interface instead of class
Can only contain public methods, variables,
and constants
Methods do not contain a body.
All methods are implicitly abstract.

01/08/16

19

Define an Interface
To distinguish an interface from a class,
Java uses the following syntax to define an
interface:
public
interface InterfaceName {
}

constant declarations;
method signatures;

public
Example
:
interface

Edible {
/** Describe how to eat */
public abstract String howToEat();

}
01/08/16

20

An Example
For instance all Vehicles should be able to
Speed up
Slow down
Turn

01/08/16

21

Some observations
Each method defined in the interface
does not have a body.
Interfaces can only have initialized
variables.
Any class that has the same methods
defined in the interface may
implement Drivable.

01/08/16

22

Implementing Interfaces

A class that uses an interface must


Use the keyword implements
Define all methods that are part of the interface
01/08/16

23

A Closer Look at Interfaces


All methods are implicitly abstract.
A class that implements an interface
must implement all methods defined in
the interface in order to be concrete.
A class that does not implement all
methods must be labeled as abstract
when appropriate.

Interfaces can be used as a reference


variable type.
All of the rules of polymorphism apply.
01/08/16

24

Example: Comparable
Comparable is an interface defined in
the Java API that is used to provide an
ordering of objects of the same type.
A class that implements comparable
must define the compareTo() method.
When invoked, a.compareTo(b) returns
a negative number if a < b
0 if a == b
a positive number if a > b
01/08/16

25

Comparable
// This interface is defined in
// java.lang package
package java.lang;
public interface Comparable {
public int compareTo(Object o);
}

01/08/16

26

An Example of Comparable

Here, we are alphabetically ordering cars by their make and


then their model.

01/08/16

27

Conventions
All interface methods must have thorough
javadoc comments. These must include the
intended purpose of the method.
compareTo is supposed to return specific
values when invoked. This is a convention of
the interface and is enforced by the Java
compiler.
The following implementation is syntactically
correct, but violates the intended usage.

01/08/16

28

String and Date Classes


Many classes (e.g., String and Date) in the Java library
implement Comparable to define a natural order for the objects.
If you examine the source code of these classes, you will see the
keyword implements used in the classes, as shown below:
public class String extends Object
implements Comparable {
// class body omitted

public class Date extends Object


implements Comparable {
// class body omitted

new
new
new
new

01/08/16

String() instanceof String


String() instanceof Comparable
java.util.Date() instanceof java.util.Date
java.util.Date() instanceof Comparable

29

Generic max Method


// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Comparable max
(Comparable o1, Comparable o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
}

// Max.java: Find a maximum object


public class Max {
/** Return the maximum of two objects */
public static Object max
(Object o1, Object o2) {
if (((Comparable)o1).compareTo(o2) > 0)
return o1;
else
return o2;
}
}
(b)

(a)

String s1 = "abcdef";
String s2 = "abcdee";
String s3 = (String)Max.max(s1, s2);

Date d1 = new Date();


Date d2 = new Date();
Date d3 = (Date)Max.max(d1, d2);

The return value from the max method is of the


Comparable type. So, you need to cast it to String or Date
explicitly
01/08/16

30

The Cloneable Interfaces


Marker Interface: An empty interface.
A marker interface does not contain constants or methods.
It is used to denote that a class possesses certain desirable
properties.

A class that implements the Cloneable interface is


marked cloneable, and its objects can be cloned
using the clone() method defined in the Object
class.

package java.lang;
public interface Cloneable {
}
01/08/16

31

Interfaces V. S. 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.
Variables

Constructors

Methods

Abstract
class

No restrictions

Constructors are invoked by subclasses


through constructor chaining. An abstract
class cannot be instantiated using the new
operator.

No restrictions.

Interface

All variables
must be public
static final

No constructors. An interface cannot be


instantiated using the new operator.

All methods must be


public abstract
instance methods

01/08/16

32

Interfaces V. S. Abstract
Classes (Cont.)
Interface1_2

Interface1_1

Object

Interface2_2

Interface1

Class1

Interface2_1

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.
01/08/16

33

Interface Hierarchy
Interfaces can be used as the base class
of other interfaces.
You can derive an interface from another
interface using the keyword extends.
A derived interface inherits all the methods of
the base interface.
To implement a derived interface, all methods
must be implemented by the class.

Since interfaces can be used as reference


variables, they can add to class
hierarchies.
01/08/16

34

Class Hierarchy

01/08/16

35

Multiple Inheritance
Java does NOT support multiple
inheritance with classes.
You can not say Class X extends X, Y

However, Java does allow a class to


implement multiple interfaces.

01/08/16

36

Multiple Interfaces

The class Liger must implement all


methods in both Lion and Tiger.
Liger can now be referenced by either Lion
or Tiger, but is limited to the interface
defined in Lion or Tiger, respectively.
01/08/16

37

Multiple Interfaces

No Java syntax errors will occur for


methods that overlap from Lion and Tiger.
But in languages like C++, many problems arise
from a Diamond of Death.
01/08/16

38

You might also like