问答详情
源自:10-1 Java 中的多态

请大神求解obj1.way()为什么会报错

public class Vehicles {       //父类


public static void main(String[] args) {


Vehicles obj1 = new Vehicles();

Vehicles obj2 = new Bus();

Vehicles obj3 = new boat();

Vehicles obj4 = new airplane();

obj1.way();   

}

}


}

public class Bus extends Vehicles {  //子类BUS

int number=50;

String name="bus";

String function="陆地";

  public  void way() {

System.out.println("载客"+number+"人的"+name+"是在"+function+"上运行的");

}

}


public class boat extends Vehicles {  //子类BUS

int number=500;

String name="boat";

String function="海洋";

  public  void way() {

System.out.println("载客"+number+"人的"+name+"是在"+function+"上运行的");

}

}

public class airplane extends Vehicles {    //子类airplane

int number=1000;

String name="airplant";

String function="天空";

void way() {

System.out.println("载客"+number+"人的"+name+"是在"+function+"上运行的");

}

}


提问者:慕沐4503986 2018-09-19 22:20

个回答

  • 慕神0064665
    2018-09-19 23:39:19
    已采纳

    obj1是父类的对象,而父类里并没有定义"way()",所以报错

  • 慕莱坞5659625
    2018-09-20 19:33:06

    是不是因为定义obj1234时,都是用父类引用的,而way是子类的方法,不能调用 视频8分12秒有讲