1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[JAVA]abstractとinterfaceの違いについて

Last updated at Posted at 2020-07-09

Java言語仕様について、面接で答えられなかったことが恥ずかしかったので再度学び直します。

interface と abstractの関係について

様々な表現方法で表す。

# interface abstract
仕様面 クラス仕様としての定義をしたいときに利用する 継承関係にあり処理を再利用させたい場合に利用する
実装クラスor具体クラスとの関係 実装クラス CAN 抽象機能 具体クラス IS 抽象クラス

コード的な違い

interface

// 抽象
public interface Cashier {
    void bill();
}

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

abstract

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

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

修飾子のスコープ

# 同一クラス 同一パッケージ サブラクス 全て
default - -
private - - -
protected -
public
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?