Free Java Tutorials >> Table of contents >> Abstract

1. Abstract Classes

Abstract Classes and Abstract Methods

An abstract class cannot be instantiated, and thus you cannot "new" an abstract class. The only way to create them is by extending them and instantiating the subclass.

Additionally, abstract classes can have abstract methods. Unlike a traditional method, the abstract method has no body (no curly brackets {}), and it ends in a semicolon. Thus, the behavior of an abstract method is defined in the subclass. In addition, the subclass must define the behavior of the method:

abstract class Animal {
	abstract void makeSound();
}
//Cannot do new Animal();
class Cat extends Animal {
	void makeSound() { //this method is required!
		System.out.println("Meow");
	}
}

Besides that, abstract classes follow all other rules of polymorphism. They are most useful when each subclass defines a different behavior, and there is no clear shared behavior besides the method signature. A common example might be a Button class, where drawing different types of buttons is performed differently. Toggle buttons, menu buttons, etc -- all may have different void display() methods. An abstract Button class would thus only define the method signature: abstract void display(). Finally, a GUI library could call the display() method on a collection of various buttons.

2. Extending Generics

Fixed type in subclass

When subclassing a generic type, you can permanently set the type parameter while extending:

class Person<T> {
	T age;
}
class Student extends Person<Integer> {}
// Now Student.age is always an Integer

In the above example, Student.age is fixed to permanently be an Integer

A generic extending a generic

You can retain a templated type by making the subclass generic:

class Person<T> {
	T age;
}
class Student extends Person<Integer> {}
class Teacher<A> extends Person<A> {}
//It is now valid to do Teacher<String>, 
//  which would set the age field to be a String

In the above example, it would have been valid to re-use the "T" character for the generic in Teacher.

Previous: Extends Super

Next: Interfaces Lambdas