Learn Java Tutorial for Beginners (Video), Part 38: Abstract Classes

Abstract classes allow you to define the parent class of a new hierarchy without having to worry about the user actually instantiating the parent. For instance you could create an "Animal" class just to act as the basis for "Dog", "Cat, "Sheep" and so on, even defining some functionality in "Animal", but at the same time preventing the user of your hierarchy from trying to create an "Animal" object (which after all wouldn't make much sense -- you never encounter an abstract "animal" in the real world; only particular kinds of animals).

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:

App.java:

 

public class App {

    public static void main(String[] args) {
        Camera cam1 = new Camera();
        cam1.setId(5);
        
        Car car1 = new Car();
        car1.setId(4);
        
        car1.run();
        
        //Machine machine1 = new Machine();
    }

}
 

Machine.java:

 
public abstract class Machine {
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    public abstract void start();
    public abstract void doStuff();
    public abstract void shutdown();
    
    public void run() {
        start();
        doStuff();
        shutdown();
    }
}

 

Camera.java:

 
public class Camera extends Machine {

    @Override
    public void start() {
        System.out.println("Starting camera.");
    }

    @Override
    public void doStuff() {
        System.out.println("Taking a photo");
        
    }

    @Override
    public void shutdown() {
        System.out.println("Shutting down the camera.");
        
    }

}
 

Car.java:

 

public class Car extends Machine {

    @Override
    public void start() {
        System.out.println("Starting ignition...");
        
    }

    @Override
    public void doStuff() {
        System.out.println("Driving...");
    }

    @Override
    public void shutdown() {
        System.out.println("Switch off ignition.");
          
    }

}