Java
Abstract reference
Learn to use objects via abstract references.
Abstract class references
An abstract class cannot be instantiated directly, but it works as a reference type. Shape s = new Circle(); is valid when Shape is abstract; this is the most powerful use. The abstract class provides a contract; subclasses supply concrete behavior.
Adding a new subclass does not change code that uses the superclass. A method process(Shape s) can receive a Circle, a Square or any future subclass; each calls the right area method.
Polymorphism with interfaces
An interface can also be a reference type. Drawable d = new Circle(); works when Circle implements Drawable. This lets you set a type contract independent of the class hierarchy.
You can implement several interfaces with implements A, B, C; this is Java's answer to multiple inheritance. Interfaces may have default methods with bodies.
Exercise Abstract Shape and concrete Circle
Define abstract class Shape with an abstract int area(); method (no body). Define class Circle extends Shape with an int r field, a Circle(int r) constructor and an overridden area method returning r * r * 3. In main, assign with Shape s = new Circle(3); and print System.out.println("Area: " + s.area());.
Show example solution
abstract class Shape {
abstract int area();
}
class Circle extends Shape {
int r;
Circle(int r) { this.r = r; }
int area() { return r * r * 3; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(3);
System.out.println("Area: " + s.area());
}
}
Test yourself
-
Match the abstract and concrete uses
- abstract class
- Cannot be instantiated; holds references
- new Circle()
- Produces a concrete instance
- interface
- Contract; allows multiple inheritance
- concrete class
- Created directly with new
-
Which is true for an abstract class?
- It can be instantiated directly with new
- It can only contain static methods
- It cannot be replaced by an interface
- It cannot be instantiated but can be a reference type
Show answer
It cannot be instantiated but can be a reference type — An abstract class cannot be instantiated but can be used as a reference.
-
Complete the interface implementation keyword
class Circle extends Shape implements ____ {
public void draw() { }
}
Show answer
class Circle extends Shape implements Drawable {
public void draw() { }
}
Next lesson: Pattern matching