Abstract classes (course memo)
Java. An abstract class describes a general idea and is deliberately unfinished — you can't instantiate it with new. Instead, you extend it into a concrete class that can be instantiated. Every subclass shares whatever non-private code the abstract class defines.
Abstract classes
java
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}abstractbeforeclass— can no longer be created withnew.- Extended (
extends) as normal.
java
public class Dog extends Animal {
private int lovePoints;
public Dog(String name, int lovePoints) {
super(name);
this.lovePoints = lovePoints;
}
public int getLovePoints() {
return lovePoints;
}
}Dog(concrete) can be instantiated;Animal(abstract) can't.- Just like with interfaces, a
Dogcan go into aList<Animal>.
Abstract methods
java
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract String move();
}abstractbefore the return type marks the method itself as unfinished — no body.- Every concrete subclass must implement it.
- An abstract method can't be
private(a private method couldn't be overridden by a subclass anyway).
java
public class Dog extends Animal {
public Dog(String name) { super(name); }
@Override
public String move() { return "The dog walks"; }
}
public class Bird extends Animal {
public Bird(String name) { super(name); }
@Override
public String move() { return "The bird flies"; }
}Interfaces vs abstract classes
Both can force implementations to have specific methods. Beyond that:
| Can do | Interface | Abstract class |
|---|---|---|
| Force specific methods | yes | yes |
| Share static properties (Java 8+) | yes | — |
| Share default/implemented methods (Java 8+) | yes | — |
| Share (instance) properties/fields | no | yes |
| Share implemented (instance) methods | limited (default methods) | yes |
(See 16-interfaces-advanced.md for what interfaces gained in Java 8.)