为什么当我抛弃我无法访问子类属性?

时间:2015-04-14 19:54:28

标签: java netbeans casting

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类'属性。

2 个答案:

答案 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方法。但是phoneMotoX类型的变量。只需使用phone代替myPhone,您就可以访问MotoX的属性。