JAVA基础(内部类)

一,内部类可以访问外部类的私有属性及方法,同样外部类也可以很轻松地访问内部类的私有属性

package 类与对象;
class Outer
{
  private String mes = "hello";
  class Inner
  {
      private String mes2 = "world";
      public void print()
      {
          System.out.println("内部类访问外部类的私有属性:"+mes);
          // System.out.println("内部类访问外部类的私有属性:"+Outer.this.mes);
          //如果用this,需要加上当前对象所属的类名即变成Outer.this
      }
  }
  public void fun()
  {
      new Inner().print();
      System.out.println("外部类访问内部类的私有属性:"+new Inner().mes2);
      
  }

}
    public class DEMO1 {
        public static void main(String[] args) {
            Outer out = new Outer();
            out.fun();
        }

        }


在这里插入图片描述
二,上述通过fun()函数来调用内部类的print()方法,内部类能否实例化一个对象直接调用print()方法?

package 类与对象;
class Outer
{
  private String mes = "hello";
  class Inner
  {
      private String mes2 = "world";
      public void print()
      {
          System.out.println("内部类访问外部类的私有属性:"+Outer.this.mes);
      }
  }

}
    public class DEMO1 {
        public static void main(String[] args) {
            Outer.Inner in = new Outer().new Inner();
            //产生内部类对象in
            in.print();


        }

    }

在这里插入图片描述
三,static定义内部类,相当于产生了一个新的外部类,只有内部类才能用static定义,外部类不能用

package 类与对象;
class Outer
{
  private static String mes = "hello";
   static class Inner
  {
      private String mes2 = "world";
      public void print()
      {
          System.out.println("内部类访问外部类的私有属性:"+mes);
      }
  }

}
    public class DEMO1 {
        public static void main(String[] args) {
            Outer.Inner in = new Outer.Inner();//此时可以吧Outer.Inner看成一个新的外部类
            //产生内部类对象in
            in.print();
        }

    }

在这里插入图片描述
四,内部类定义在方法中,可以调用方法中的参数及局部变量

package 类与对象;
class Outer
{
  public void fun(int temp) {
      int temp1 = 100;
      class Inner {
          public void print() {
              System.out.println("fun()中的参数temp = " + temp);
              System.out.println("fun()中的局部变量temp1 = " + temp1);
          }
      }
      new Inner().print();
  }
}
    public class DEMO1 {
        public static void main(String[] args) {
           Outer out = new Outer();
           out.fun(100);
        }

    }

在jdk1.8及其以后在方法中定义内部类,当内部类调用该方法的参数及局部变量时,参数与变量声明时可以不加final。如果是jdk1.8之前的版本需要加final!
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值