今天在学习的时候我发现定义的内部类如果不用static修饰的话是无法调用构造器实例化的,这是为什么?
而且如果内部类先于外部类被加载进内存,那不是越俎代庖的行为吗?
class Example2 {
class Telephone {
String brand;
String number;
double dialledTime;
double rate;
double balance;
public Telephone(String brand, String number, double balance) {
this.brand = brand;
this.number = number;
this.balance = balance;
}
public Telephone() {
}
public void recharge(double cost) {
balance = balance + cost;
System.out.println("冲值后的余额:" + balance);
}
public void callCost() {
double callcost = dialledTime * rate;
balance = balance - callcost;
System.out.println("话费:" + callcost);
System.out.println("余额:" + balance);
}
public void display() {
System.out.println("电话品牌:" + brand + "电话号码:" + number);
System.out.println("通话时间:" + dialledTime + "费率:" + rate);
}
}
Telephone tel = new Telephone( );
// Telephone tel;
public static void main(String[] args) {
Telephone tel;
tel = new Telephone("TCL", "8309600", 100);
tel.rate = 0.2;
tel.dialledTime = 150;
tel.display();
tel.callCost();
tel.recharge(50);
}
}
内部类不加static只能声明该类的指针或引用。
static代表该类所有对象所共有,它好像是在类加载后再构造的。