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类'属性。
答案 0 :(得分:1)
myPhone
被定义为CellPhone
。如果您想使用Motox
方法,则应将其定义为Motox
:
Motox myPhone = new MotoX("motorola", "white", true, 5);
或者在使用时明确地施放它:
CellPhone myPhone = new MotoX("motorola", "white", true, 5);
((Motox) myPhone).someMotoxMethod();
答案 1 :(得分:1)
您使用了错误的变量。您试图从myPhone
访问MotoX方法。但是phone
是MotoX
类型的变量。只需使用phone
代替myPhone
,您就可以访问MotoX
的属性。