问题:
前面我们构建了一个商品类Merchandise,里面包含了一些属性。 此时因业务需要,我们需要创建一个手机类Phone,同时需要包含Merchandise里的属性和方法,又不想手动的复制代码到Phone类里,怎么办呢?
答案是: 继承
- 继承: 类名后面加extends 类名。
- 被继承的类叫做父类
- 继承者叫做子类
- Java中每一个类只能有一个父类
- 子类继承了父类的什么呢? 属性和方法
- 子类不能访问父类的private 属性和方法。
二、通过继承实现父类属性及方法的使用。
Q: 初始化一个Phone对象,并把该对象的售价,库存等输出出来。
A: 代码如下
<TestPhone.java>
public class TestPhone {
public static void main(String[] args) {
Phone phone = new Phone(6.0,3.5,8.0,128.0,"小米", "安卓");
phone.setId(1);
phone.setName("小米9");
phone.setCount(100);
phone.setSoldPrice(3999);
phone.setPurchasingRrice(3599);
phone.describe();
}
}
<Phone.java>
public class Phone extends Merchandise {
// 给phone 增加新的属性和方法:
private double screenSize;
private double cpuHZ;
private double memoryG;
private double storageG;
private String brand;
private String os;
public Phone(double screenSize, double cpuHZ, double memoryG, double storageG, String brand, String os) {
this.screenSize = screenSize;
this.cpuHZ = cpuHZ;
this.memoryG = memoryG;
this.storageG = storageG;
this.brand = brand;
this.os = os;
}
@Override
public void describe() {
super.describe();
System.out.println("手机配置信息如下:\n屏幕大小:" + this.screenSize + "英寸 \nCPU主频:" + this.cpuHZ + "GHz \n内存大小:" + this.memoryG + "G \n存储空间:" + storageG + "G \n品牌:" + this.brand + " \n操作系统:" + os);
}
public double getScreenSize() {
return screenSize;
}
public double getCpuHZ() {
return cpuHZ;
}
public double getMemoryG() {
return memoryG;
}
public double getStorageG() {
return storageG;
}
public String getBrand() {
return brand;
}
public String getOs() {
return os;
}
public void setScreenSize(double screenSize) {
this.screenSize = screenSize;
}
public void setCpuHZ(double cpuHZ) {
this.cpuHZ = cpuHZ;
}
public void setMemoryG(double memoryG) {
this.memoryG = memoryG;
}
public void setStorageG(double storageG) {
this.storageG = storageG;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void setOs(String os) {
this.os = os;
}
}
网友评论