了解Java中的方法重载和重写

我知道方法重载意味着在子类中定义与父类同​​名的方法,但具有不同的参数,方法重载意味着在子类中定义具有与父类完全相同的签名的方法。

However, I feel I miss some understanding. I tried some examples. I defined two classes A and B extends A. Then I prepared many examples with different combinations of two methods (method(A) and method(B)) they can contain. For example:

  • Example 1: A contains both method(A) and method(B) and B contains none
  • Example 2: A contains method(A) and B contains method(B)

等等。可以有16种这样的组合。

Now I created two instances of class B and called various methods on first instance. I can go for creating various combinations of instances and method calls also but that will be overwhelming number of combinations to prepare examples.

令人怀疑的是,我正在努力猜测一些示例的输出结果。或者更具体地说,我错过了理解,或者我应该说最少的规则集,这些规则可以决定所有示例中的输出。混淆是由于引用类型与它所引用的实例类型不同而引起的。所以我没有得到哪种方法优先,一种是引用类型,另一种是实例类型。在以下示例中,我没有获得示例3、4和5的输出。这些仅是可能的16种组合中的5种。我相信可能会有一些更令人困惑的组合。

以下是一些例子

示例1 –向下转换会产生编译时错误

class A {
    public void method(B b)
    {
        System.out.println("A's method(B)");
    }
}

class B extends A { 
    public void method(B b)
    {
        System.out.println("B's method(B)");
    }
}
A a = new B();
B b = new B();
a.method(b); //outputs B's method(B)
a.method(a); //compile time error: The method method(B) in the type A 
            //is not applicable for the arguments (A)

示例2 –如果需要,可以进行上播

class A {
    public void method(A a) 
    {
        System.out.println("A's method(A)");
    }
}

class B extends A {
    public void method(A a) 
    {
        System.out.println("B's method(A)");
    }
}

A a = new B();
B b = new B();
a.method(b);
a.method(a);

输出量

B's method(A)  //upcasting happening
B's method(A)

例子3

class A {
    public void method(A a) 
    {
        System.out.println("A's method(A)");
    }

    public void method(B b)
    {
        System.out.println("A's method(B)");
    }
}

class B extends A {
    public void method(A a) 
    {
        System.out.println("B's method(A)");
    }
}

A a = new B();
B b = new B();
a.method(b);
a.method(a);

输出量

A's method(B)
B's method(A)

例子4

class A {
    public void method(A a) 
    {
        System.out.println("A's method(A)");
    }

    public void method(B b)
    {
        System.out.println("A's method(B)");
    }
}

class B extends A {
    public void method(A a) 
    {
        System.out.println("B's method(A)");
    }

    public void method(B b)
    {
        System.out.println("B's method(B)");
    }
}

A a = new B();
B b = new B();
a.method(b);
a.method(a);

输出量

B's method(B)
B's method(A)

例子5

class A {
    public void method(A a) 
    {
        System.out.println("A's method(A)");
    }
}

class B extends A {
    public void method(A a) 
    {
        System.out.println("B's method(A)");
    }

    public void method(B b)
    {
        System.out.println("B's method(B)");
    }
}

A a = new B();
B b = new B();
a.method(b);
a.method(a);

输出量

B's method(A)
B's method(A)