繁体   English   中英

将对象转换为子类型时找不到符号

[英]cannot find symbol when casting an object to a subtype

如果它是CastTest的实例,则尝试编写一个将从Object生成新CastTest对象的构造函数,就像这样(x是CastTest的实例变量):

public CastTest(Object theTestObj)  
    {
        if (theTestObj instanceof CastTest) {
            //this.x = theTestObj.x; // Error: cannot find symbol: variable x ???
            //this.x = (CastTest) theTestObj.x; // Error: cannot find symbol: variable x ???
            //this.x = theTestObj.getX(); // Error: cannot find symbol: method getX() ???
            //this.x = (CastTest) theTestObj.getX(); // Error: cannot find symbol: method getX() ??? 
        }
    }

为什么找不到变量或方法? 它们在相同的类定义中定义。

实例变量根据引用的声明类型进行解析。 Object没有x实例字段。 正确的演员是

((CastTest)theTestObj).x
// this whole expression is of type CastTest which seems to have a field x

你有什么,这个

(CastTest) theTestObj.x;

相当于

(CastTest) (theTestObj.x)

与前面解释的问题相同

theTestObj.x

暂无
暂无

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

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