Skip to content

Activity 11: Abstract Classes

Instructions

Example Code

Model 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class ToySheep {
    private int volume;

    public ToySheep() {
        this.volume = 3;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
        makeNoise();
    }

    public void makeNoise() {
        System.out.println("Baaa");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ToyRobot {
    private int chargeLevel;
    private int volume;

    public ToyRobot() {
        this.chargeLevel = 5;
        this.volume = 10;
    }

    public void recharge() {
        chargeLevel = 10;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
        makeNoise();
    }

    public void makeNoise() {
        System.out.println("Beep Beep!");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Main {

    public static void main(String[] args) {

        LoudToy toy1 = new LoudToy(1);
        toy1.setVolume(5);

        LoudToy toy2 = new ToySheep();
        toy2.setVolume(5);

        LoudToy toy3 = new ToyRobot();
        toy3.setVolume(5);
    }
}
Model 2 (wait to download)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public abstract class LoudToy {
    private int volume;

    public LoudToy(int volume) {
        this.volume = volume;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
        makeNoise();
    }

    public abstract void makeNoise();
}
Model 3 (wait to download)
1
2
3
4
5
6
7
public interface Rechargeable {
    int MAX_CHARGE = 10;

    int getCharge();

    void recharge();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class CellPhone implements Rechargeable {
    private int chargeLevel;
    private int volume;

    public CellPhone(int chargeLevel, int volume) {
        this.chargeLevel = chargeLevel;
        this.volume = volume;
    }

    public int getCharge() {
        return chargeLevel;
    }

    public void recharge() {
        chargeLevel = MAX_CHARGE;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public void makeCall() {
        System.out.println("Ring... Hello?");
    }
}