繁体   English   中英

使用super作为引用类型时,无法访问子类中的方法

[英]Can't access methods in sub class when using the super as the reference type

我有一个上课的问题

 public class Foo {

   public Foo() {
    // Do stuff
   }

   public void generalMethod() {
      //to general stuff
   }

 }

 public class Bar extends Foo {

     public Bar() {
        //do stuff
     }

     public void uniqueMethod() {
        //do stuff
     }
 }


 public class Driver() {
    public static void main(String[] args) {
       Foo test = new Bar();

       test.uniqueMethod(); //this causes an error
    }
 }

所以我得到一个错误,它说Foo的方法uniqueMethod()是未定义的,但是当我将赋值更改为Bar test = new Bar(); 问题消失了。 我不明白,因为它应该与Foo test = new Bar();

有人可以提出导致此错误的原因吗?

先感谢您。

尽管该方法在运行时存在,但编译器仅看到类型为Foo的对象test不具有方法uniqueMethod。 Java使用虚拟方法,其中将在runtime确定要调用的方法。 因此,再次,编译器看不到该特定实例的类型是Bar 如果确实需要调用该方法,则可以强制转换并调用该方法:

((Bar)test).uniqueMethod();

现在,对于编译器,您具有Bar类型,他可以看到Bar类型可用的所有方法。

像编译器和JVM一样思考

例子1

Foo test = new Bar();

因此,我有一个Foo类型的变量。 我必须验证对该类成员的所有后续调用都可以 -它将查找Foo类中的所有成员,编译器甚至不查找实例类型。

runtime ,JVM将知道我们有一个类型为Foo的变量,但实例类型为Bar 唯一的区别在于,JVM(JVM)将查找实例以对方法进行虚拟调用

例子2

Bar test = new Bar();

因此,我有一个Bar类型的变量。 我必须验证对该类成员的所有后续调用都可以 -它将查找Foo和'Bar'类中的所有成员,再次,编译器甚至不查找实例类型。

runtime ,JVM将知道我们有一个Bar类型的变量和一个相同类型的实例: Foo 现在我们再次可以访问FooBar类中定义的所有成员。

使用后期绑定,您必须在超类“ Fathor”中具有相同的方法,否则将不起作用!

与我一起工作

//

public  class foo {
public void print(){
System.out.println("Super,"+2);}

}

bo类扩展foo {

    public void print(){
        System.out.println("Sup,"+9);
        }

}

测试//

公共抽象类测试{

public static void main(String[] args) {
    // TODO Auto-generated method stub

     foo t = new bo();
     t.print();
}

} ///

输出

一口9

发生此错误的原因是,编译器不知道test的类型是Bar ,而只知道Foo的声明类型。

public void test(Foo foo) {
        // error! this method can accept any variable of type foo, now imagine if you passed it 
        // another class that extends Foo but didnt have the uniqueMethod. This just wont work
        foo.uniqueMethod(); 
    }

暂无
暂无

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

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