java学习笔记18——内部类

  外部类的上一级程序单元是包,所以它只有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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值