欢迎光临散文网 会员登陆 & 注册

静态内部类的使用

2022-06-26 19:45 作者:虚云幻仙  | 我要投稿

/**
* 测试静态内部类的使用
*/

public class Outer2 {
   public int age = 10;
   public static int speed = 20;
   public static String name = "aa";
   public int money = 100;

   public static class Inner2{
       //添加static修饰变成静态内部类
       public int age = 20;
       public int speed = Outer2.speed + 10;
       //静态变量speed属于类 不用加this.

       public void pr(){
           System.out.println(speed);
           System.out.println("Inner2.pr");
           System.out.println(Outer2.speed);
           //无法调用Outer2.age 静态内部类中只能调用外部类的静态内容
           System.out.println(name);
           //内部类中没有定义name时会调用Outer2.name
       }
   }
}

class TestInner2{
   public static void main(String[] args) {
       Outer2 o2 = new Outer2();
       Outer2.Inner2 i2 = new Outer2.Inner2();
       //静态内部类通过外部类调用 不通过外部类的对象
       i2.pr();
       //Inner2是static 但Inner2内的age speed是成员变量 pr()是非静态方法 都属于对象
   }
}

静态内部类的使用的评论 (共 条)

分享到微博请遵守国家法律