帮我看一下这个java程序,求救求救!!!!为什么父类没有无参构造方法就报错
public class Test1 {public static void main(String[] args)
{
Vehicle c1=new Car1(4,5.5,4);
c1.show();
}
}
class Vehicle{
int wheel;
double weight;
public Vehicle()
{
wheel=4;
weight=2;
}
public void show(){
System.out.println("车轮个数:"+wheel+"车重:"+weight);
}
}
class Car1 extends Vehicle{
int loader;
public Car1(){}*************(这个不可以没有)
public Car1(int wheel,double weight,int loader)
{
this.wheel=wheel;
this.weight=weight;
this.loader=loader;
}
public void show()
{
System.out.println("小车的车轮个数"+wheel+" 车重:"+weight+" 载人个数:"+loader);
}
}
class Truck extends Car1{
double payload;
public Truck(int wheel,double weight,int loader,double payload)
{
this.wheel=wheel;
this.weight=weight;
this.loader=loader;
this.payload=payload;
System.out.println("卡车的车轮个数:"+wheel+" 车重:"+weight+" 载人个数:"+loader+" 载重:"+payload);
}
}
为什么??? --------------------编程问答-------------------- class Truck extends Car1因为你这里继承了Car1但是又没有对你类进行初始化
正确写法是:
public Truck(int wheel,double weight,int loader,double payload)
{
super(wheel,weight,loader);
this.wheel=wheel;
this.weight=weight;
this.loader=loader;
this.payload=payload;
System.out.println("卡车的车轮个数:"+wheel+" 车重:"+weight+" 载人个数:"+loader+" 载重:"+payload);
} --------------------编程问答-------------------- 每个类构造的时候默认有个
public 类名(){}的构造方法;但是自己显示的写了一个构造方法的话,原来的那个构造方法就没有了;
比如你又写了构造方法叫做
public 类名(int i){};此时就没有了原来那个方法
当子类继承自父类的时候,写了一个构造方法的话,、、、、、哎呀,太过了,懒的说了;
public Truck(int wheel, double weight, int loader, double payload) {
/**
* 它会默认调用super();这个方法,也就是父类的无参构造方法;
* 但是如果你没有这个方法,就会报错,所以你只有用另一个已经定义好的有参构造来覆盖原来的super();
*/
super(wheel, weight, loader);
this.wheel = wheel;
this.weight = weight;
this.loader = loader;
this.payload = payload;
System.out.println("卡车的车轮个数:" + wheel + " 车重:" + weight + " 载人个数:"
+ loader + " 载重:" + payload);
}
//没说详细,不管了、、、、呵呵呵呵、、
补充:Java , Java EE