Java 为什么当我向下转换时无法访问子类属性?
我知道向下转换可以将一个超级类转换为一个更具体的子类型,但是当我这样做时,我无法访问MotoX类的属性。Java 为什么当我向下转换时无法访问子类属性?,java,netbeans,casting,Java,Netbeans,Casting,我知道向下转换可以将一个超级类转换为一个更具体的子类型,但是当我这样做时,我无法访问MotoX类的属性。myPhone被定义为手机。如果要使用Motox方法,应将其定义为Motox: class Casting { main() { //instantiate the subclass MotoX CellPhone myPhone = new MotoX("motorola", "white", true, 5); MotoX p
myPhone
被定义为手机。如果要使用Motox
方法,应将其定义为Motox
:
class Casting
{
main()
{
//instantiate the subclass MotoX
CellPhone myPhone = new MotoX("motorola", "white", true, 5);
MotoX phone = (MotoX) myPhone;
//I tried to call MotoX methods using myPhone
//however netbeans only showed the properties within the CellPhone class
}
}
或在使用时显式强制转换它:
Motox myPhone = new MotoX("motorola", "white", true, 5);
您使用了错误的变量。您试图从myPhone
访问MotoXmethods。但是,phone
是类型为MotoX
的变量。只需使用phone
而不是myPhone
,您就可以访问MotoX
的属性。OP做了一个明确的向下转换。@Turing85-onphone
。这无助于他在myPhone
上调用方法。谢谢!那么,像我这样向上投射有什么意义呢?(手机myPhone=new MotoX();)@Bryan你得到了抽象。您可以稍后使用任何其他手机实现替换myPhone
的实例,并保持其余代码不变。我开始理解,因此,如果我这样做,例如,(MotoX phone=(MotoX)myPhone;)那么“phone”变量将被分配给myPhone变量?这样做有什么意义?@Bryan我想你对继承有一个普遍的误解。如果您有一个类型为mobile
的变量(无论分配给它什么),则只能访问类mobile
中定义的方法。另一方面,向下转换允许您访问子类已知的方法,而不是超类已知的方法。
CellPhone myPhone = new MotoX("motorola", "white", true, 5);
((Motox) myPhone).someMotoxMethod();