Java构造器和构造方法的意义是什么?有什么用?
运行结果看有两个问题不明白:
1、为什么A[1]、A[2]可以调用toString方法,A[3]不能调用x方法?
2、输出的这串字符“Car@12204a1”是什么意思?地址吗?
父类Car
public class Car
{
public String name;
public double price;
public int id;
public int num;
public double weight;
public Car(int id,String name,double price,int num,double weight)//构造器不能加void
{
this.id=id;
this.name=name;
this.price=price;
this.num=num;
this.weight=weight;
}
public String x()
{
return id+" "+name+" "+price+" "+num+" "+weight;
}
}
子类getManCar
class getManCar extends Car
{
public getManCar(int id,String name,double price,int num)
{
super(id, name, price, num, 0);
}
public String toString()
{
return id+" "+name+" "+price+" "+num+" "+0;
}
}
运行下面程序
Car[] A=new Car[3];
A[0]=new getManCar(1,"奥迪A4",500.0,4);
A[1]=new getManCar(2,"马自达6",400.0,4);
A[2]=new Car(3,"皮卡雪6",400.0,4,2.0);
for(int i=0;i<A.length;i++)
{
System.out.println(A[i]);
}
得到结果
1 奥迪A4 500.0 4 0
2 马自达6 400.0 4 0
Car@12204a1