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被定义为CellPhone。如果要使用Motox方法,则应将其定义为Motox

Motox myPhone = new MotoX("motorola", "white", true, 5);


或在使用时显式转换它:

CellPhone myPhone = new MotoX("motorola", "white", true, 5);
((Motox) myPhone).someMotoxMethod();

10-07 16:31