30、静态内部类
2021-04-18 本文已影响0人
爱学习的代代
静态内部类是在一个类中定义类。(public static class
内部类)
好处是:
- 减少类的可见性,减少Java source源文件的数量,让相关的类都集中在一个文件里
- 在内部类里访问外部类的属性(private属性)
- 外部的类可以访问内部的类,内部的类也可以外部类的属性。
代码示例:
package day16;
public class PhoneV2 extends MerchandiseWithConstructor{
private double screenSize;
private CPU cpu;
private double memoryG;
private double storageG;
private String brand;
protected String os;
// 给手机品类增加个数限制
private static int MAX_BUY_COUNT = 5;
public PhoneV2(int id, String name, int count, double soldPrice, double purchasingRrice,
double screenSize, double memoryG, double storageG, String brand, String os) {
// 因为父类的属性不是公开的需要set方法来进行设置
super(id,name,count,soldPrice,purchasingRrice);
this.screenSize = screenSize;
this.memoryG = memoryG;
this.storageG = storageG;
this.brand = brand;
this.os = os;
}
public static class CPU {
private double speed;
private String producer;
public CPU(double speed, String producer) {
this.speed = speed;
this.producer = producer;
}
public double getSpeed() {
// 内部类和这个类本身的访问情况是一样的,可以访问外部类的private属性
// PhoneV2 ph = null;
// ph.memoryG = 99;
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
}
// 单独实现子类对于购买数量的限制
// 在子类中声明同样的方法(返回值、方法名、入参)
public double buy(int count) {
if (count > MAX_BUY_COUNT) {
System.out.println("超出商品的单词购买上限,购买失败");
return -1;
}
return super.buy(count);
}
public void describe() {
super.describe();
System.out.println("手机配置信息如下:\n屏幕大小:" + this.screenSize + "英寸 \n" + " \n内存大小:" + this.memoryG + "G \n存储空间:" + storageG + "G \n品牌:" + this.brand + " \n操作系统:" + os);
}
public double getScreenSize() {
return screenSize;
}
public void setScreenSize(double screenSize) {
this.screenSize = screenSize;
}
public double getMemoryG() {
return memoryG;
}
public void setMemoryG(double memoryG) {
this.memoryG = memoryG;
}
public double getStorageG() {
return storageG;
}
public void setStorageG(double storageG) {
this.storageG = storageG;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
}
测试代码:
package day16;
public class TestPhoneV2 {
public static void main(String[] args) {
PhoneV2 v2 = new PhoneV2(200,"小米10",200,3999,3599,6,8.0,128.0,"小米","Android");
v2.describe();
PhoneV2.CPU cpu = new PhoneV2.CPU(5.5, "intel");
System.out.println(cpu.getProducer());
System.out.println(cpu.getSpeed());
}
}
运行结果:
image.png
除了静态内部类,还有成员内部类,局部内部类,由于使用的比较少,这里不再进行赘述。等需要用到的时候再去了解。