LoginSignup
4
1

More than 5 years have passed since last update.

メソッドの引数が継承/実装関係にあった場合のオーバーロード

Last updated at Posted at 2017-09-17

Javaで継承/実装関係にあるクラスのオーバーライドでは実行時に型が決定してメソッドが呼び出されますが、オーバーロードではどのメソッドが呼び出されるのかを調べてみました

インタフェース

public interface OInterface {
    public void printClassname();
}

親クラス

public class OParent  {
    public void printClassname() {
        System.out.println("called:OParent=>printClassname()");
    }
}

子クラス(インタフェースを実装)

public class OChild extends OParent implements OInterface {

    @Override
    public void printClassname() {
        System.out.println("called:OChild=>printClassname()");
    }
}

実行用コード

public class OverloadMain {
    public static void main(String[] args) {

        OverloadMain main = new OverloadMain();

        OChild child = new OChild();
        OParent parent = new OChild();
        OInterface iface = new OChild();

        main.overloadMethod(child);  // (1)
        System.out.println("----");
        main.overloadMethod(parent); // (2)
        System.out.println("----");
        main.overloadMethod(iface);  // (3)
    }


    public void overloadMethod(OChild child) {
        System.out.println("called:overloadMethod(OChild)");
        child.printClassname();
    }

    public void overloadMethod(OParent parent) {
        System.out.println("called:overloadMethod(OParent)");
        parent.printClassname();
    }

    public  void overloadMethod(OInterface iface) {
        System.out.println("called:overloadMethod(OInterface)");
        iface.printClassname();
    }
}

予想
予想1. (1)~(3)は全てoverloadMethod(OChild child)呼ばれる(オーバーライドと同じ)
予想2. (1)~(3)はそれぞれ宣言した型のメソッドが呼ばれる

実行結果

called:overloadMethod(OChild)
called:OChild=>printClassname()
----
called:overloadMethod(OParent)
called:OChild=>printClassname()
----
called:overloadMethod(OInterface)
called:OChild=>printClassname()

結論

予想2. (1)~(3)はそれぞれ宣言した型のメソッドが呼ばれる
でした
オーバーロードはコンパイル時にに決定するのですね

4
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
4
1