[Java] [JAVA] Difference between abstract and interface

1 minute read

I was embarrassed that I could not answer the Java language specification at the interview, so I will re-learn again.

Regarding the relationship between interface and abstract

Expressed in various ways.

# interface abstract
Specification Used when you want to define as class specification Used when you want to reuse the process because of inheritance relationship
Implementation class or relationship with concrete class Implementation class CAN abstract function Concrete class IS abstract class

Code differences

interface

// abstract
public interface Cashier {
    void bill();
}

// Implementation class 1
public class CreditCart implements Cashier {
    public CreditCart(){
    }
    @Override
    public void bill(){
        System.out.println("billed by credit card");
    }
}
// Implementation class 2
public class Cash implements Cashier {
    @Override
    public void bill() {
        System.out.println("billed by cash");
    }
}

abstract

// abstract class
public abstract class Animal {
    String name;
    public Animal(String name) {
        this.name = name;
    }
    public void sleep() {
        System.out.println("Sleeping");
    }
    public abstract void speak();
}

// Implementation class 1
public class Human extends Animal {
    public Human(String name) {
        super(name);
    }
    @Override
    public void speak() {
        System.out.println(name + "speack human languages");
    }
}
// Implementation class 2
public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
    @Override
    public void speak() {
        System.out.println(name + "speack cat's language");
    }
}

Modifier scope

# Same class Same package Sublux All
default - -
private - - -
protected -
public

Tags:

Updated: