内部类(成员内部类、静态内部类、方法内部类、匿名内部类)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zhi_19950628/article/details/81065191

内部类分为三种:成员内部类,静态内部类,方法内部类,匿名内部类。

成员内部类:成员内部类在类中相当于类的成员。(就相当于类内部的一个成员)

        特点:成员内部类可以访问外部类的所有成员,并且内部类可以在外部类中被new,并能够访问外部类的成员

        注意:如果内部类被声明为私有的,外界将无法访问。

例子:class Outer{

             private int num=4;                //定义内部类的成员变量

             public void test(){

              Inner inner=new Inner();

              inner.show();

      }

class Inner{

      void show(){

         System.out.println("num="+num);

           }

     }

}

public  class Example{

   public  Static void main(String[] args){

          Outer outer=new Outer();

          outer.test();

     }

}

如果想通过外部类去访问内部类成员需要通过外部类的对象去创建内部类的对象

外部类的名称.内部类的名称 变量名=new外部类的名称().new 内部类的名称();

例:

public  void  mian {

      public static void mian(String [] args){

            Outer.Inter inter=new Outer().new Inter();

            inner.show();

  }

}

静态内部类:

      静态内部类就是加 static 关键字的成员内部类,他可以在不创建外部类对象的情况下被实例化

      语法格式:外部类名.内部类名 变量名=new 外部类名。内部类名();

      特点:静态内部类只能访问外部类的静动态数据成员

class persion{

  public static int num=4;

  static class Inner(){

        void show(){

        System.out.pringln("num="+num);

}

}

}

class  Example18{

         public  static void mian(String [] args){

              Outer.Inner inner=new Outer.Inner();

               inner.show();

}

}

方法内部类:   方法内部类只能在当前方法中使用(是指写在方法内部的)

class Outer{

  private  int num=4;

 peivate  void test(){

  class Innter{

      void show(){

            System.out.println("num="+num);

}

}

Innter innter=new Innter();

innter.show();

}

}

public class Example(){

public ststic void main(String[] args){

  Outer outer =new Outer();

   outer.test();

}

}

匿名内部类:就是不直接写类的名字,直接在方法的()写出类的实现,方法相当于声明。这就相当于对接口进行了实现

例:interface Animal{

               void shout(); 

}

public class Example{

   public  static void mian(String [] args){

       animalShout(new Animal(){

          //实现shout的方法

          public void shout(){

            System.out.println("喵喵。。。。");

}

});

}

public static void animalShout(Animal an){

                    an.shout();

}

这大概就是对内部累的全部总结,如有不懂的欢迎大家留言

猜你喜欢

转载自blog.csdn.net/Zhi_19950628/article/details/81065191