今天周六,本以为能多写代码。结果只是白天看了一天的视频,晚上写个商店类还没写完。写了父类Shop,子类SeedShop和ConstructionShop。只对子类 的属性进行了赋值。还没有编写方法。
试了下一种把子类的属性直接写定。一种是把子类的属性在无参构造函数内写定。这两者在创建对象的语法上是没有区别,但不太懂在一些细节方面有什么区别呢?通过试错学到一点:子类定义了和父类同名变量后,在子类构造函数中给变量赋值是赋给了子类的变量,这时用父类的get()方法调用,只能得到null。那么看来给子类定义同名属性不管怎么赋值都是给子类的属性赋值。而且父类的get/set方法也就没有意义了。因此完全不必在定义同名属性。既然是继承,那就全都继承。其实是白天看视频学过的知识,但是真实听过不等于记住,更不等于掌握,还是要自己多敲代码来体验。
package shop;
public class Shop {
public String shopName;
public String[] itemList;
public float[] pricesArray;
public Shop() {
}
// public Shop(String shopName, String[] itemList, float[] pricesArray) {
// super();
// this.shopName = shopName;
// this.itemList = itemList;
// this.pricesArray = pricesArray;
// }
public float[] getPrices() {
return pricesArray;
}
public void setPrices(float[] prices) {
this.pricesArray = prices;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String[] getItemList() {
return itemList;
}
public void setItemList(String[] itemList) {
this.itemList = itemList;
}
}
package shop;
public class SeedShop extends Shop{
public SeedShop() {
super.shopName = "种子公司";
super.itemList =new String[] {"番茄种子","土豆种子","玉米种子","南瓜种子",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null};
super. pricesArray = new float[]{1.0F,1.0F,1.0F,1.0F,2.0F,2.0F,2.0F,2.0F,3.0F,3.0F,3.0F,3.0F,4.0F,4.0F,4.0F,4.0F,5.0F,5.0F,5.0F,5.0F};
}
public void welcomBuy() {
System.out.println("欢迎光临" + shopName + "您想购买什么?");
for(int i = 0;i<itemList.length;i++) {
if(itemList[i] != null)
System.out.print((i+1)+ "." +itemList[i] + " 每个 " + pricesArray[i] + "元。");
}
System.out.println();
}
public void SecretBuy() {
System.out.println("如果升级会有新东西出售。");
}
}
package shop;
public class ConstructionShop extends Shop {
public ConstructionShop() {
shopName = "建筑公司";
itemList = new String[]{"农场升级1-2","农场升级2-3","农场升级3-4","农场升级4-5"};
pricesArray = new float[]{100,200,400,800};
}
}
惭愧惭愧。与目标想去甚远。一是水平确实不行,写的时候一直在测试各种用法。二是需求没定,框架没搭,边写边想。效率低。希望明天能把商店类写好。下周就可以写交互界面了。