子类与父类属性设置

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()构造对象,正常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值