Sub topic 2
Declaring an Abstract Class
In the last chapter you saw the idea of abstraction: describing what something does without saying exactly how. Java gives you two tools for this. This chapter covers the first one, the abstract class. You will learn how to write one, what the abstract keyword changes, and what the compiler will and will not let you do with it.
What Is an Abstract Class?
An abstract class is a class that you mark with the keyword abstract. It describes a general idea, and you cannot create an object directly from it. You use it as a parent for other classes.
Think about the word "animal." You have seen dogs, cats, and birds. You have never seen an animal that was only an "animal" and nothing more specific. "Animal" is a general idea, and real things are always some particular kind of animal.
An abstract class works the same way. Animal can be the general idea. Dog and Cat are the real things you make objects from.
A class you can make objects from is called a concrete class. Every class you have written so far has been concrete.
The Syntax
To make a class abstract, put the word abstract before class:
abstract class Animal {
public void breathe() {
System.out.println("Breathing in and out");
}
}That is the whole change. The class can still have methods with bodies, like breathe() here. A method with a body is called a concrete method.
You can also write the modifiers in this order, and it means the same thing:
public abstract class Animal {
// ...
}Most Java code puts the access modifier (public) first and abstract second.
Rule 1: You Cannot Create an Object of an Abstract Class
Instantiate means "create an object from a class with new." An abstract class cannot be instantiated. This is the main rule.
Animal a = new Animal(); // compile errorThe Java compiler stops and reports an error like this:
error: Animal is abstract; cannot be instantiatedThis is a compile error, which means the program never runs. Java catches the mistake before your code ever starts. That is a good thing, because the error shows up early, while you are still writing the code.
Making an Abstract Class Useful
If you cannot make an object from it, what is it for? You extend it. Another class inherits from it with extends, and you make objects from that class instead.
Here is a complete program you can run:
abstract class Animal {
public void breathe() {
System.out.println("Breathing in and out");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.breathe(); // inherited from Animal
d.bark();
Animal a = new Dog(); // an Animal variable holding a Dog
a.breathe();
// Animal bad = new Animal(); // compile error: Animal is abstract
}
}Output:
Breathing in and out
Woof!
Breathing in and outLook at the line Animal a = new Dog();. The variable has the type Animal. The object is a Dog. That works because a Dog is an Animal. The thing that is not allowed is new Animal().
Rule 2: An Abstract Class Does Not Need Abstract Methods
The next chapter introduces abstract methods, which are methods with no body. Abstract classes often contain them. But they are not required. The Animal class above has zero abstract methods, and it is still a legal abstract class.
Why would you do that? Sometimes you want shared code in a parent class, but an object of the parent alone would make no sense. Marking the class abstract makes Java stop anyone from creating one by mistake.
The rule goes the other way too: if a class does contain an abstract method, the class must be marked abstract. You will see this in the next chapter.
Rule 3: `abstract` and `final` Do Not Mix
The keyword final on a class means "no class may extend this one." An abstract class exists to be extended. So the two words contradict each other:
abstract final class Animal { } // compile errorThe compiler reports:
error: illegal combination of modifiers: abstract and finalAn abstract class that could never be extended could never be used, so Java forbids it.
What an Abstract Class Can Contain
An abstract class is still a class. Apart from the "no new" rule, it can hold almost everything a normal class can.
| Item | Allowed in an abstract class? | Notes |
|---|---|---|
| Concrete methods | Yes | Subclasses inherit them. |
| Abstract methods | Yes | Covered in the next chapter. |
| Fields (variables) | Yes | Covered in a later chapter. |
| Constructors | Yes | Run when a subclass object is created. |
| Static methods | Yes | Called as `Animal.someMethod()`. |
| `new` on the class itself | No | Compile error. |
| `final` on the class | No | Conflicts with `abstract`. |
Constructors may seem odd, since you cannot call new Animal(). They still run whenever a subclass object is built. A later chapter explains this in detail.
Common Mistakes
- Trying to instantiate it.
new Animal()fails. Create a subclass object instead. - Thinking the type name is forbidden.
Animal a = new Dog();is fine. Onlynew Animal()is blocked. - Adding
final. Never combineabstractandfinalon a class. - Forgetting the keyword. If you leave out
abstract, Java treats the class as concrete, and anyone can create objects from it.
Summary
- Write
abstract class Nameto declare an abstract class. - You cannot create an object of it with
new. The compiler blocks this. - You use it by extending it with a concrete subclass.
- You can still use it as a variable type that holds subclass objects.
- It can contain concrete methods, fields, constructors, and static methods.
- It may have zero abstract methods.
- It cannot be
final.
Exercise
Will this code compile? If not, which line fails and why? abstract class Vehicle { public void start() { System.out.println("Starting"); } } class Bike extends Vehicle { } Line A: Vehicle v = new Bike(); Line B: Vehicle w = new Vehicle();
Show answer
Line A compiles, because a Bike is a Vehicle and a variable of an abstract type can hold a subclass object. Line B fails with "Vehicle is abstract; cannot be instantiated", because you cannot use new on an abstract class.
Exercise
A classmate writes "public abstract final class Shape { }". What does the compiler say, and why does the rule exist?
Show answer
The compiler reports "illegal combination of modifiers: abstract and final". An abstract class can only be used by extending it, and final forbids extending, so the class could never be used.
Exercise
Is this a legal abstract class? abstract class Tool { public void use() { System.out.println("Using tool"); } }
Show answer
Yes. An abstract class does not need any abstract methods. Marking it abstract only prevents code from creating a Tool object directly, while subclasses still inherit use().