1.方法的签名和重载` 
public double buy() {
return buy(1);
}
public double buy(int count) { return buy(count, false);
}
public double buy(int count, boolean isVIP) {
if (this.count < count) {
return -1;
}
this.count -= count;
double totalCost = count * soldPrice;
if (isVIP) {
return totalCost * 0.95;
} else {
return totalCost;
}
}
在该类里面,有三个签名:buy(),buy(int count)和buy(int count, boolean isVIP)。这就叫方法重载。;
2.重载的参数匹配规则 
public class MerchandiseV2AppMain {
public static void main(String[] args) {
MerchandiseV2 merchandise = new MerchandiseV2();
merchandise.init("书桌", "DESK9527", 40, 999.9, 500);
int count = 3;
System.out.println("测试使用不完全匹配的参数调用重载方法");
double countForOverride = 11;
merchandise.buy(countForOverride);
}
}
在调用有重载的类的方法的时候(其他类的方法也一样),并不是需要所有参数类型都匹配才会调用方法,在上面的代码块的TODO 中,说到,会按照byte,short ,long,float,double这样的顺序去调用,也就是说如果参数是byte类型,但是方法体有short和double类型时,会先自动调用short类型的方法体;
3.构造方法 
public class MerchandiseV2WithConstructor {
public String name;
public String id;
public int count;
public double soldPrice;
public double purchasePrice;
public MerchandiseV2WithConstructor(String name, String id, int count,
double soldPrice, double purchasePrice) {
this.name = name;
this.id = id;
this.count = count;
this.soldPrice = soldPrice;
this.purchasePrice = purchasePrice;
}
在我们new一个对象的时候,会有一个括号:
MerchandiseV2WithConstructor merchandise = new MerchandiseV2WithConstructor();
其实这个括号就是用来给构造方法传参数的; 只是一般用java官方类的时候,都默认不用传参数, 但是我们自己定义构造方法的时候,java就不会再添加无参数的构造方法 这样我们在创建对象的时候,就要给构造方法传参数了;
public class RunLittleSupperMarketAppMain {
public static void main(String[] args) {
LittleSuperMarket littleSuperMarket = new LittleSuperMarket(
"有家小超市", "浦东新区世纪大道666号",
100, 200, 200);
System.out.println("下面请利润最高的商品自我介绍:");
littleSuperMarket.getBiggestProfitMerchandise().describe();
}
}
构造方法也可以重载 
public class MerchandiseV2 {
public String name;
public String id;
public int count = 999;
public double soldPrice;
public double purchasePrice;
public MerchandiseV2(String name, String id, int count, double soldPrice, double purchasePrice) {
this.name = name;
this.id = id;
this.count = count;
this.soldPrice = soldPrice;
this.purchasePrice = purchasePrice;
}
public MerchandiseV2(String name, String id, int count, double soldPrice) {
this(name, id, count, soldPrice, soldPrice * 0.8);
}
public MerchandiseV2() {
this("无名", "000", 0, 1, 1.1);
}
首先说一下为什么"子类的构造方法, 会强制在第一行调用父类的构造方法", 这个我在视频里提了一嘴, (人工划重点)这是因为子类可以访问父类的方法和属性. 那么必须保证子类的对象在做任何事情之前, 子类里那个隐含的父类对象, 必须初始化完成. 否则, 初始化都没完成, 调用方法, 返回属性, 都可能得到的是不对的状态/值(人工划重点结束).
|