package FruitBox;
public class Fruit {
String name; //colorname
@Override
public String toString() {
return this.getClass()+" weight is:"+this.weight+",name is:"+this.name;
}
double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public Fruit(String name, double weight) {
super();
this.name = name;
this.weight = weight;
}
public Fruit(double weight) {
super();
this.weight = weight;
}
public Fruit() {
super();
}
}
package FruitBox;
public class Apple extends Fruit{
// String name; //colorname
// double weight;
// public Apple(double weight) {
// name="red";
// super(weight);
// // TODO Auto-generated constructor stub
// }
public Apple(String name, double weight) {
super(name, weight);
// this.name = name;
// this.weight = weight;
}
public Apple() {
super();
// TODO Auto-generated constructor stub
}
public Apple(double weight) {
super(weight);
// TODO Auto-generated constructor stub
}
}
package FruitBox;
import java.util.*;
public class Test {
public static void main(String[] args) {
Apple apple = new Apple("red",9);
FruitBox fb = new FruitBox();
System.out.println(apple);
System.out.println(apple);
System.out.println(apple.name+" "+apple.weight);
// fb.addFurit(apple);
// fb.fruitInfo();
// apple = new Apple("red",2.7);
// fb.addFurit(apple);
// fb.fruitInfo();
}
}
写代码时把构造函数写在父类里面,但是在子类中又重写了父类中包含的属性,导致在创建对象时其属性一直为空,执行报空指针异常,但定义在父类中的
toString函数嫩正常运行,说明创建的对象保存了父类中的属性,但调用时被子类覆盖,由于时间原因未深究对象如何获取该属性
在子类中增加属性赋值语句后,正常显示,但是toString任显示的是父类属性
注销掉子类中的属性,super()构造对象,正常