Abstract class can be enforced by adding abstract method, method can be created as usual ⇒ By inheriting, you can forcibly attach a subclass method. In other words, by giving the derived class the same method and forcibly creating the method You can create a class that gives you coercion
The team has a common tax rate method in the class A, which everyone uses. Regional taxes vary from region to region, so make a method with individual derived classes.
⇒ A class that implements an interface can be put in the interface box. In other words, if you implement an interface, you can switch between A and B depending on the conditions.
Sample (interface)
public interface ControlPanelIf {
void play();
void pause();
void stop();
void forwardFast();
void backwordFast();
}
The class that implements this is the following code.
Actually, it is often more complicated, but let's write it as a sample.
public class DvdDeck implements ControlPanelIf {
@Override
public void play() {
System.out.println("DVD playback");
}
@Override
public void stop() {
System.out.println("DVD playback stop");
}
@Override
public void pause() {
System.out.println("DVD pause");
}
@Override
public void forwardFast() {
System.out.println("DVD fast forward");
}
@Override
public void backwardFast() {
System.out.println("DVD fast rewind");
}
}
The class that uses this DVDDeck class is as follows.
public class DeckUser {
public static void main(String[] args) {
ControlPanelIf myDeck = createDeck(args[0]);
myDeck.play();
myDeck.forwardFast();
myDeck.pause();
myDeck.play();
myDeck.backwardFast();
}
private static ControlPanelIf createDeck(String deckType) {
ControlPanelIf deck;
if(deckType.equals("DVD") {
deck = new DvdDeck();
} else if(deckType.equals("BluRay") {
deck = new BluRayDeck();
} else if(deckType.equals("HDD") {
deck = new HddRayDeck();
} else {
deck = new DvdDeck();
}
return deck;
}
}
Reference material https://www.slideshare.net/graminmakeall/java-43178044?qid=6a49c149-fcb0-4aa8-87d0-2e4e2c18362b&v=&b=&from_search=5
Recommended Posts