java内部类(成员)(课堂)



        //////////////////成员内部类 ///////////////////////

 

/**

 *成员内部类(放在成员里)

 *1、内部类的修饰符跟普通的属性或方法一样

 *2、内部类对象的创建

 *  Outer outer = new Outer();

 *  Inner inner = outer.newInner();

 *3、内部类属性的访问顺序  内部类局部  ---内部类成员----外部类成员

 *4、内部类方法跟属性访问顺序一致,而且可以访问outer中所有的类型的

 *  权限修饰的方法或者属性

 *5、普通的内部类不能定义static方法跟static属性,如果属性使用staticfinal进行

 *  一起修饰属性时,可以存在,因为static + final表示常量

 *

 *内部类的运用场景:

 *  1、如果一个类加工数据结构比较复杂,可以使用内部类辅助创建数据类型结构

 *  2、功能上 如果一个功能非常复杂,需要使用内部类进行辅助实现

 *

 */

 

 

publicclass Outer {              //定义外部类

 private Stringinfo ="hello";//定义外部类的私有方法

 publicinta = 1;      //基本属性

 publicstaticintb = 10;//静态属性,静态方法才能访问

 privatevoid method(){  //私有成员方法

   System.out.println("Other.method");

 }

 

 publicclass Inner{           //定义内部类

   publicinta = 2;

   publicstaticfinal Stringage ="111";//常量

   //public staticint b = 2;//出错

  

   publicvoid innermethod(){     //定义内部类的方法

     System.out.println(b); //能调用外部类的b

     method();    ///能调用成员方法

     inta = 3;

     System.out.println(a);//内部类成员--3

     System.out.println(this.a);//内部类成员--2

     System.out.println(Outer.this.a);//外部类成员--1

    

     //类比跨包访问

    

     /*int a = 1;

     //public static int b= 2;//出错

     Outer outer = new Outer();

     Inter inter =new Inter();

     inter.mether();

     System.out.println();

     */

     System.out.println(info);////直接访问外部类的私有属性////

   }

  

   //The method staticInnerMethod cannot bedeclared static; static

       //methods can only be declared in a static ortop level type

       /*public static void staticInnerMethod(){

        System.out.println(b);

       }*/

  

 }

 

 publicvoid fun(){              //定义外部类的方法

   newInner().innermethod();       //通过内部类的实例化对象调用方法

 }

 

 publicstaticvoid main(String[]args) {

   new Outer().fun();          //调用外部类的fun方法,与下面的调用方式一样,觉得下面那种好理解

  

   //Inner inner2 = new Outer().new Inner();

  

   Outer outer =new Outer();//创建一个指向new Outerouter对象

   Inner inner =outer.new Inner();//创建一个指向outer.new Inner()inner对象

   inner.innermethod();//inner调用innermethod()方法

 }

 

}

 

你可能感兴趣的:(内部类,java--内部类)