Interfaces and Abstract Classes in Java
Objectives
- Distinguish between interfaces, abstract classes, and concrete
classes
- Know and understand the purpose of an interface and an abstract
class
- Know what is allowed in an interface, an abstract class, and a
concrete class
Prerequisites
Definitions
- abstract method
- A method without a body (only a header
followed by a semicolon)
- concrete method
- A normal method; a method with a body
- interface
- A class-like entity that has only class
(static) data and abstract methods
- abstract class
- A class that cannot be used to create
objects (cannot be instantiated) and may have abstract methods
- concrete class
- A normal class; a pattern or blueprint for creating objects
Purpose
- An interface is used as a parent in a realizes hierarchy and as
the type of a reference variable.
- An abstract class is used as the parent in an inheritance
hierarchy and as the type of a reference variable.
Rules
- It is not possible to create an object from an interface or
abstract class.
- Interfaces may not contain instance data.
- Interfaces may not contain concrete instance methods.
- Concrete classes may not contain abstract instance
methods.
- There is no such thing as an abstract class method. It doesn't
make sense.
- Summary
|
(most abstract) |
|
(least abstract) |
|
interface |
abstract class |
concrete class |
| Can be instantiated |
|
|
√ |
| May contain class data |
√ |
√ |
√ |
| May contain instance data |
|
√ |
√ |
| May contain class methods |
√ |
√ |
√ |
| May contain abstract instance methods |
√ |
√ |
|
| May contain concrete instance methods |
|
√ |
√ |
Example
import java.awt.Graphics2D;
interface Drawable {
public static final double SPARKLE_COEFFICIENT = 0.26; // class data
public void draw(Graphics2D g); // abstract method
}
class ChessBoard implements Drawable {
public void draw(Graphics2D g) { // concrete method
// actual code here
}
}
abstract class ChessPiece implements Drawable {
protected String color;
public abstract boolean move(int location); // abstract method
}
class King extends ChessPiece {
private boolean moved = false; // instance data
public boolean move(int location) { // concrete method
// actual code here
moved = true;
// actual return statement here
return true;
}
public void draw(Graphics2D g) { // concrete method
// actual code here
}
}
class Queen extends ChessPiece {
public boolean move(int location) { // concrete method
// actual code here
// actual return statement here
return true;
}
public void draw(Graphics2D g) { // concrete method
// actual code here
}
}
class Pawn extends ChessPiece {
public boolean move(int location) { // concrete method
// actual code here
// actual return statement here
return true;
}
public void draw(Graphics2D g) { // concrete method
// actual code here
}
}
Copyright © 2010, Maia L.L.C. All rights reserved.