zoukankan      html  css  js  c++  java
  • 成员内部类

    内部类相当于外部类的一个成员,和其它成员处于同一个级别,因此可以在内部类中直接访问外部类的各个成员(包括私有属性)。
    需要注意的是在外部类中要想访问内部类的各个成员(这里也包括内部类的私有属性)就必须先实例化内部类,然后才能访问。对于为什么能访问内部类的私有属性,是因为即使内部类的成员是私有的,但是也是在外部类中,和外部类的其它成员是平等的,只不过被内部类囊括是在内部中,因此访问都必须先实例化。

    public class Outerclass {
    
      private static int outStatic = 0;
      private int out;
    
      private Outerclass(){
        this.out = 1;
      }
      class Inner{
    
        private int in;
        private Inner(){
          this.in = 2;
        }
    
        private void innerVoidMethod(){
          System.out.println(Outerclass.this.outStatic);//0
          System.out.println(Outerclass.this.out);//1
          System.out.println(Inner.this.in);//2
          System.out.println(this.in);//2
          Outerclass.outerStaticMethod();//outerStaticMethod
          Outerclass.this.outerVoidMethod();//outerVoidMethod
        }
        //private static void innerStaticMethod(){} //error,当内部类中有静态方法或者静态成员变量时,一定是静态内部类
      }
    
      private void outerVoidMethod(){
        System.out.println("outerVoidMethod");
      }
      private static void outerStaticMethod(){
        System.out.println("outerStaticMethod");
      }
      public static void main(String[] args) {
        new Outerclass().new Inner().innerVoidMethod();//内部类的实例需要先实例化外部类
      }
    }
  • 相关阅读:
    iOS开发>学无止境
    iOS开发>学无止境
    iOS开发>学无止境
    Objective-C学习—UITableView的使用
    iOS开发>学无止境
    iOS开发—AFNetworking的使用
    iOS开发>学无止境
    c#笔记(六)——数组(2)
    c#笔记(六)——数组
    c#笔记(五)——循环结构
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/7884552.html
Copyright © 2011-2022 走看看