Help us understand the problem. What is going on with this article?

interfaceを実装したクラスでメソッドをオーバーライドする時

More than 5 years have passed since last update.

interfaceで定義したメソッドは暗黙でpublic abstractになるので、
オーバーライドしたメソッドには必ずpublicを付ける

Sample.java
interface Inter
{
    void methodX(); // public abstract
}

class ImpleInter implements Inter
{
    public void methodX() // public 付けないとダメ
    {
        System.out.println("ImpleInter");
    }
}

class Sample
{
    public static void main(String[] args)
    {
        Inter i = new ImpleInter(); // interface型の変数にオブジェクトの参照を代入
        i.methodX();
    }
}

じゃないと

Sample.java:8: ImpleInter の methodX() は Inter の methodX() を実装できません。スーパークラスでの定義 (public) より弱いアクセス特権を割り当てようとしました。
    void methodX()
         ^
エラー 1 個

参照型の型変換
interface名 変数名 = インターフェースを実装したオブジェクト

Inter i = new ImpleInter(); // interface型の変数にオブジェクトの参照を代入

呼び出し側でインターフェースを実装したクラスがなくても、インターフェース型の変数を用意してメソッドを呼び出すことができる。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした