java学习笔记18——内部类

来源:互联网 发布:2017淘宝蓝海类目 编辑:程序博客网 时间:2024/06/05 17:04
  外部类的上一级程序单元是包,所以它只有2个作用域:同一个包内和任何位置。因此只需要2种访问权限:包访问权限和公开访问权限,正好对应省略访问控制符和public访问控制符。省略访问控制符是包访问权限,即同一包中的其他类可以访问省略访问控制符的成员。如果一个外部类不适用任何控制符修饰,则只能被同一个包中其他类访问。而内部类的上一级程序单元是外部类,它有4个作用域:同一个类、同一个包、父子类和任何位置。
例        
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 setLength(double length){
this.length = length ;
}
public double getLength(){
return this.length;
}
public void setColor(String color){
this.color = color;
}
public String getColor(){
return this.color;
}
public void info(){
System.out.println("当前牛腿颜色是:"+color+",高:"+length);
System.out.println("本牛腿所在奶牛重:"+weight);
}
}
public void test(){
CowLeg c1 = new CowLeg( 1.12 "黑白相间");
c1.info();
}
public static void main(String[] args){
Cow cow = new Cow(378.9);
cow.test();
}
}

        非静态内部类的成员可以访问外部类的private成员,但反过来就不成立。非静态内部类的成员只在非静态内部类范围内是可知的,不并能被外部类直接使用。如果外部类需要访问非静态内部类的成员,则必须显示创建非静态内部类对象来调用访问其实例成员
public class Outer{
private int outProp = 9;
class Inner{
private int inProp = 5;
public void accessOuterProp(){
System.out.println("外部类的outPut值:"+outProp);
}
}
public void accessInnerProp{
System.out.println("内部类的inProp值:"new Inner().inProp);
}
public static void main(String[] args){
Outer out = new Outer();
out.accessInnerProp();
}
}

        非静态内部类对象必须寄存在外部类对象里,而外部类对象则不必一定有非静态内部类对象寄存其中。如果存在一个非静态内部类对象,则一定存在一个被它寄存的外部类对象。静态成员不能访问非静态成员。 
        外部类的静态方法、静态代码块不能访问非静态内部类,包括不能使用非静态内部类定义变量、创建实例等。总之,不允许在外部类的静态成员中直接使用非静态内部类。
        也就是main函数里不能创建非静态内部类实例。
public class StaticTest{
private class In{}
public static void main(String[] args){
// new In();  错误,静态成员不能访问非静态成员。
}
        注意,非静态内部类里不能定义静态成员,即静态方法、静态成员变量、静态初始化块。
0 0