You are on page 1of 27

Abstract Classes & Interfaces

Lecture 6
Abstraction

refers to the act of representing


essential features without
including the background details
or explanations.
Abstract Classes
• Java allows abstract classes
– use the modifier abstract on a class header to
declare an abstract class
abstract class Vehicle
{ … }
• An abstract class is a placeholder in a class
hierarchy that represents a generic concept
Vehicle

Car Boat Plane


3/28/2007 Lecture 6
Abstract Classes
• Abstract classes are only used as super classes
• Abstract classes can not be instantiated - Classes are
declared as abstract classes only if they will never be
instantiated
• Abstract classes contain usually one or more abstract
methods
• Example:
public abstract class Mouse implements Direction {

abstract void makeMove( );
}
• In fact, any class with an abstract method is
automatically an abstract class
3/28/2007 Lecture 6
Abstract Methods

• Abstract methods have no body at all and just


have their headers declared
• The only way to use an abstract class is to
create a subclass that implements each abstract
method
• Concrete classes are classes that implement
each abstract method in their superclasses
• Example:
abstract void makeMove( );

3/28/2007 Lecture 6
Example abstract class
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference();
// semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor

//Implementations of abstract methods.

public double area() { return PI*r*r; }


public double circumference() { return 2*PI*r; }
}

3/28/2007 Lecture 6
Example abstract class (cont’d)

class Rectangle extends Shape {


protected double w, h; // Instance data

public Rectangle(double w, double h) { // Constructor


this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor

// Implementations of abstract methods.


public double area() { return w*h; }
public double circumference() { return 2*(w + h); }
}

3/28/2007 Lecture 6
Abstract Class: Example
• An abstract class often contains abstract
methods, though it doesn’t have to
– Abstract methods consist of only methods
declarations, without any method body
public abstract class Vehicle
{
String name;

public String getName()


{ return name; } \\ method body
abstract public void move(); \\no body!
}
3/28/2007 Lecture 6
Abstract Classes
• The non-abstract child of an abstract class
must override the abstract methods of the
parent
• An abstract class cannot be instantiated
(why?)

The use of abstract classes is a design


decision; it helps us establish common
elements in a class that is too general to
instantiate
3/28/2007 Lecture 6
Interfaces

Lecture 7
Single vs. Multiple Inheritance
• Some object-oriented languages allow
multiple inheritance, which allows a class to
be derived from two or more classes,
inheriting the members of all parents
• The price: collisions, such as the same
variable name, same method name in two
parents, have to be resolved
• Java decision: single inheritance, meaning
that a derived class can have only one parent
class
3/28/2007 Lecture 6
Java Interface
• A Java interface is a collection of
constants and abstract methods
– abstract method: a method header without a
method body; we declare an abstract
method using the modifier abstract
– since all methods in an interface are
abstract, the abstract modifier is usually
left off

• Methods in an interface have public


visibility by default
3/28/2007 Lecture 6
Interface: Syntax
interface is a reserved word

public interface Doable


{
public static final String NAME;

public void doThis();


public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}

A semicolon immediately
follows each method header
No method in an
3/28/2007 Lecture 6 interface has a definition (body)
Implementing an Interface
• A class formally implements an interface by
– stating so in the class header in the
implements clause
– a class can implement multiple interfaces:
the interfaces are listed in the implements
clause, separated by commas

• If a class asserts that it implements an


interface, it must define all methods in the
interface or the compiler will produce errors

3/28/2007 Lecture 6
Implementing Interfaces
public class Something implements Doable
{
public void doThis ()
{ implements is a
// whatever reserved word
}

public void doThat ()


{ Each method listed
// whatever in Doable is
} given a definition

// etc.
}

public class ManyThings implements Doable, AnotherDoable


3/28/2007 Lecture 6
Interfaces: An Example
• A class that implements an interface
can implement other methods as well

3/28/2007 Lecture 6
Interfaces: Examples from
Java Standard Class Library

• The Java Standard Class library defines many


interfaces:
– the Iterator interface contains methods that allow
the user to move through a collection of objects easily
• hasNext(), next(), remove()

– the Comparable interface contains an abstract


method called compareTo, which is used to compare
two objects

if (obj1.compareTo(obj2) < 0)
System.out.println(“obj1 is less than
obj2”);
3/28/2007 Lecture 6
Polymorphism via Interfaces
• Define a polymorphism reference through
interface
– declare a reference variable of an interface type
Doable obj;

– the obj reference can be used to point to any object


of any class that implements the Doable interface

– the version of doThis depends on the type of object


that obj is referring to:
obj.doThis();
3/28/2007 Lecture 6
Interface Hierarchies
• Inheritance can be applied to interfaces as well
as classes
• One interface can be used as the parent of
another
• The child interface inherits all abstract methods
of the parent
• A class implementing the child interface must
define all methods from both the parent and
child interfaces
• Note that class hierarchies and interface
hierarchies are distinct (they do not overlap)
3/28/2007 Lecture 6
Interfaces (cont’d)
• An interface in Java is like an abstract class,
but it does not have any fields or constructors,
and all its methods are abstract.
public interface Dance
{
DanceStep getStep (int i);
int getTempo ();
int getBeat (int i);
}

• “public abstract” is not written because all the


methods are public abstract.
3/28/2007 Lecture 6
Interfaces (cont’d)
• We must “officially” state that a class
implements an interface.
• A concrete class that implements an interface
must supply all the methods of that interface.
public class Waltz implements Dance
{
...
// Methods:
public DanceStep getStep (int i) { ... }
public int getTempo () { return 750; }
public int getBeat (int i) { ... }
...
}
3/28/2007 Lecture 6
Interfaces (cont’d)
• A class can implement several interfaces.
• Like an abstract class, an interface
supplies a secondary data type to objects
of a class that implements that interface.
• You can declare variables and parameters
of an interface type.
Dance d = new Waltz( );

• Polymorphism fully applies to objects


disguised as interface types.
3/28/2007 Lecture 6
Interfaces (cont’d)
public interface Edible public class Pancake
{ implements Edible
String getFoodGroup(); {
int getCaloriesPerServing(); ...
} }

public class Breakfast


Polymorphism:
{
the correct
private int myTotalCalories = 0;
method is called
...
for any specific
public void eat (Edible obj, int servings)
type of Edible,
{
e.g., a Pancake
myTotalCalories +=
obj.getCaloriesPerServing () * servings;
}
...
3/28/2007} Lecture 6
Classes Interfaces
Similarities

• An interface provides
• A superclass
provides a secondary a secondary data type
to objects of classes
data type to objects
that implement that
of its subclasses.
interface.
• An abstract class
cannot be • An interface cannot
be instantiated.
instantiated.

3/28/2007 Lecture 6
Classes Interfaces
Similarities

• A concrete subclass of • A concrete class that


an abstract class must implements an
define all the inherited interface must define
abstract methods. all the methods
specified by the
interface.
• A class can extend • An interface can
another class. A extend another
subclass can add interface (called its
methods and override superinterface) by
some of its adding declarations of
superclass’s methods. abstract methods.
Classes Interfaces
Differences

• A class can extend only • A class can implement


one class. any number of
interfaces.
• An interface cannot
• A class can have fields. have fields (except,
possibly, some public
static final constants).

• A class defines its own • An interface has no


constructors (or gets a constructors.
default constructor).
3/28/2007 Lecture 6
Classes Interfaces
Differences

• A concrete class has all • All methods declared


its methods defined. An in an interface are
abstract class usually abstract.
has one or more abstract
methods.

• Every class is a part of a • An interface may


hierarchy of classes with belong to a small
Object at the top. hierarchy of
interfaces, but this is
not as common.
3/28/2007 Lecture 6

You might also like