简体   繁体   English

为什么在父类中必须强制有一个子方法以引用父类的引用来调用它,该父类引用子类的对象?

[英]Why is it mandatory to have a child method in Parent class to call it with a reference of parent class which is referring to an object of child class?

public class A
{  }

public class B extends A
{
  public void add()
  {
   System.out.println("add in B");
  }
}

Now here if we call add in following way hen it gives an error: A a1 = new B; 现在在这里,如果我们通过以下方式调用add,则会产生错误:A a1 = new B; a1.add(); a1.add();

But when we add the add() method in class A and then call in the similar fashion then add() method of child class is called. 但是,当我们在类A中添加add()方法,然后以类似的方式调用时,子类的add()方法将被调用。

ie

public class A
{
  public void add()
  {
   System.out.println("add in A");
  }
}

public class B extends A
{
  public void add()
  {
   System.out.println("add in B");
  }
}

call: 呼叫:

A a1 = new B;
a1.add();

output: 输出:

add in B 加B

Why is it so? 为什么会这样呢?

at the method invocation of a1.add() the compiler checks if the method is present. 在a1.add()的方法调用中,编译器将检查该方法是否存在。 But it only knows that a1 is a reference to an object of class A, which does not have that method. 但是它只知道a1是对不具有该方法的类A的对象的引用。 So the compilation fails. 因此编译失败。

In this trivial example it would probably be easy for the compiler to deduct the correct type. 在这个简单的示例中,编译器可能会很容易推断出正确的类型。 But in more general cases it wouldn't. 但在更一般的情况下,事实并非如此。 And therefore this kind of logic is not part of the specs. 因此,这种逻辑不属于规范的一部分。

Because java does not know at compile time that a1 will refer to an instance of B at runtime. 因为java在编译时不知道a1在运行时将引用B的实例。 It only knows the declared type, so it only allows calls that work with the declared type. 它仅知道声明的类型,因此仅允许使用声明的类型的调用。

When the Java compiler looks at the reference a1 , it knows what methods are available. 当Java编译器查看参考a1 ,它知道可用的方法。 In your first example, class A does not have add() in its API. 在第一个示例中,类A的API中没有add() It is legal in this case to perform a cast of a1 to B like so: 在这种情况下,将a1B是合法的,如下所示:

((B)a1).add(); ((B)A1)。新增();

and the compiler will not complain. 并且编译器不会抱怨。

您希望在声明的类型A的对象上调用方法,但仅在A的子类B中实现它。在这种情况下,通常将A作为抽象类,并在A中将add()声明为抽象方法。

Good answers...I had a doubt too regarding this but now I am clear :) And one more thing ..you don't have to go into the trouble of declaring an abstract method,just make an empty method with the same name and signature in your parent class and " voila " all compilation errors are gone ;) 好的答案...我对此也有疑问,但现在我很清楚:)还有一件事..您不必费力声明一个抽象方法,只需创建一个同名的空方法和父类中的签名和“瞧”,所有编译错误都消失了;)

In your case you can add a void add(){} method like this and you wont have any problems 在您的情况下,您可以像这样添加一个无效的add(){}方法,这样就不会有任何问题

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

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