[Java] Difference between interface and abstract class

1 minute read

Difference between interface and abstract class

Abstract class

Abstract class can be forced by attaching 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 Create a class that has a force

The team uses the tax rate method that everyone uses in the class A, but it is common. Regional tax differs depending on the region, so make a method with each derived class.

interface

⇒ A class that implements an interface can be put in the interface box. In other words, if you implement the interface, you can switch between A and B depending on the condition.

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 ("Stop DVD playback");
    }

    @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 reverse");
    }
}
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

Tags:

Updated: