一、非静态内部类
package fang1;
public class Cow {
private double weight;
public Cow () {}
public Cow (double weight){
this.weight = weight;
}
private class CowLeg{
private double length;
private String color;
public CowLeg() {};
public CowLeg(double length, String color) {
this.length = length;
this.color = color;
}
public void info() {
System.out.println("当前牛腿颜色是:"+color+",高:"+length);
System.out.println("本牛腿所在奶牛重:"+weight);
}
}
public void test() {
CowLeg cl = new CowLeg(1.12,"黑白相间");
cl.info();
}
public static void main(String [] args)
{
Cow cow = new Cow(378.9);
cow.test();
}
}
输出结果:
当前牛腿颜色是:黑白相间,高:1.12
本牛腿所在奶牛重:378.9
成员内部类是一种与成员变量、方法、构造器和初始化块相似的类成员。
内部类(成员内部类)作为其外部类的成员,可以使用private、protected和public等修饰。
内部类可以直接访问外部类的私有数据,因为内部类被当成外部类的成员,同一个类的成员之间是可以相互访问的。
但外部类不能访问内部类的是实现细节,例如内部类的成员变量。