Java Abstraction
Abstraction is a way to hide how a class works and show only what it offers. An abstract class cannot be created directly, and a child class supplies the missing method bodies.
A child supplies the missing body
Animal declares sound with no body. Dog supplies the body.
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}An abstract class can hold a normal method
The sleep method has a body in Animal. Dog inherits that method as written.
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.sleep();
}
}
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Zzz");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}Creating an abstract class is refused
The first line in main tries to create an Animal object. The compiler refuses the program.
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound();
}
}
abstract class Animal {
abstract void sound();
}Example
public class Main {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
circle.label();
}
}
abstract class Shape {
abstract void draw();
void label() {
System.out.println("A shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}Key points
- The abstract keyword marks a class as abstract.
- No object can be created from an abstract class directly.
- An abstract method has a heading and no body.
- A child class supplies a body for each abstract method it inherits.
- An abstract class can also hold normal methods with bodies.
In this example, Shape is an abstract class with one abstract method. Circle supplies the body of draw. The label method already has a body in Shape, so Circle inherits it as written. Both calls print their lines.
Note
A variable can still use the abstract class as its type and hold a child object.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What must a child class do with an abstract method it inherits?