简体   繁体   English

Java中的方法重载和继承

[英]Method overloading and inheritance in java

I have the following program but it wont compile: 我有以下程序,但无法编译:

public class A {

    public void method() {
        System.out.println ("bla");
    }
}

class AX extends A {

    public void method(int a) {
        System.out.println ("Blabla");
    }

    public static void main(String[] args) {
        A a2 = new AX();
        a2.method(5);
    }
}

Why doesn't a2.method(5) use the subclasses method? 为什么a2.method(5)不使用子类方法? Isn't this method overloading? 这个方法不是重载吗?

Only methods of class A are visible to the compiler. 只有AA方法对编译器可见。 This is because your Object a2 is of type A according to A a2 = new AX(); 这是因为你的对象a2的类型为A根据A a2 = new AX(); . If you change this line to AX a2 = new AX(); 如果将此行更改为AX a2 = new AX(); it will work. 它会工作。

Maybe you confuse terms overloading and overriding . 也许您会混淆术语overloadingoverriding

Overloading is adding a different method with same name as existing one, that differs in input parameters and return type. Overloading将添加与现有名称相同的另一种方法,该方法的输入参数和返回类型有所不同。 It has nothing to do with inheritance. 它与继承无关。 From the inheritance point of view overloading is just adding a new method. 从继承的角度来看,重载只是添加一种新方法。 Your class A has no idea, what it's successors new methods are. 您的A类不知道,它是新方法的继任者。

Overriding is replacing a method with a different implementation. Overriding是将方法替换为其他实现。 A knows that there exists a method, therefore you can change it in it's successor AX . A知道存在一个方法,因此可以在其后继AX中对其进行更改。

You have two possibilities. 您有两种可能性。 Either define public void method(int a) in A : A定义public void method(int a)

public class A {

    public void method() {
        System.out.println ("bla");
    }

    public void method(int a) {
        System.out.println ("Blabla from A");
    }
}

or use AX 或使用AX

AX a2 = new AX();
a2.method(5);

because the only class, that knows about the public void method(int a) is AX . 因为唯一知道public void method(int a)AX

In Java visibility determined by Object type , not by Reference type . 在Java中,可见性取决于Object type ,而不是Reference type

In your case: 在您的情况下:

A a2 = new AX();

Object type A, so compiler can't find method(int a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM