Interfaces and Abstract Classes in Java

Objectives

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

Rules

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.