# Template.java
public abstract class Template {
public boolean isOn;
public Template() {
this.isOn = false;
}
abstract void welcome();
abstract void turnOn();
abstract void turnOff();
public final void setup() {
if (!isOn) {
welcome();
turnOn();
}
}
public final void toggleSwitch() {
if (this.isOn)
turnOff();
else {
welcome();
turnOn();
}
}
}
# PC.java
public class PC extends Template {
@Override
void welcome() {
System.out.println("Welcome to My PC!");
}
@Override
void turnOn() {
super.isOn = true;
System.out.println("PC is on.");
}
@Override
void turnOff() {
super.isOn = false;
System.out.println("PC is off.");
}
}
# TV.java
public class TV extends Template {
@Override
void welcome() {
System.out.println("Welcome to My TV!");
}
@Override
void turnOn() {
super.isOn = true;
System.out.println("TV is on.");
}
@Override
void turnOff() {
super.isOn = false;
System.out.println("TV is off.");
}
}
# Main.java
public class Main {
public static void main(String[] args) {
PC pc = new PC();
// startup and welcome screen
pc.setup();
// PC off
pc.toggleSwitch();
// startup and welcome screen again
pc.toggleSwitch();
System.out.println("====================");
TV tv = new TV();
tv.setup();
tv.toggleSwitch();
}
}
# 결과
Welcome to My PC!
PC is on.
PC is off.
Welcome to My PC!
PC is on.
====================
Welcome to My TV!
TV is on.
TV is off.
댓글 영역