简体   繁体   English

使用Object变量实例化子类时,无法从超类访问方法

[英]Cannot access method from superclass when subclass instantiated using Object variable

I was practising inheritance and had these classes where Bite extends the Gulp class. 我正在练习继承,并在Bite扩展Gulp类的这些类中学习。

public class Gulp {
    public void method2() {
        System.out.println("Gulp 2");
        method3();
    }

    public void method3() {
        System.out.println("Gulp 3");
    }
}

public class Bite extends Gulp {
    public void method1() {
        System.out.println("Bite 1");
    }

    public void method3() {
        System.out.println("Bite 3");
    }
}

I am trying to invoke the method method2() by creating objects of Bite class(using three different kind of references: Object,Bite and Gulp) as below: 我试图通过创建Bite类的对象(使用三种不同类型的引用:Object,Bite和Gulp)来调用方法method2() ,如下所示:

public class Main {
    public static void main(String[] args) {
        Object varObj = new Bite();
        Bite varBite = new Bite();
        Gulp varGulp = new Bite();

        if(varBite.getClass() == Bite.class) 
            System.out.println("Bite class");

        if(varObj.getClass() == Bite.class) 
            System.out.println("Also Bite class");

        varBite.method2();
        //prints what is expected

        varObj.method2();
        //throws compilation error -- cannot find method2()

        varGulp.method2();
        //prints what is expected
    }
}

I am getting error when the reference variable is type of Object. 当引用变量是对象类型时,出现错误。 It says, it cant find the symbol although the varObject.getClass() returns Bite.class. 它说,尽管varObject.getClass()返回Bite.class,但它找不到符号。 Could anyone please explain.. 任何人都可以解释一下。

The compiler won't let you call methods specific to Bite if you declared the variable as of type Object . 如果您将变量声明为Object类型,则编译器将不允许您调用特定于Bite方法。

You have two options: Either declare the objects as Bite , like varBite . 您有两种选择:像varBite一样,将对象声明为Bite Or cast the Object variable to Bite : 或将Object变量BiteBite

((Bite)varObj).method2();

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

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