美文网首页程序员
你一定要知道Java中4种类型的内部类

你一定要知道Java中4种类型的内部类

作者: 程序员麦冬 | 来源:发表于2020-07-09 15:53 被阅读0次

    在Java中有4种不同类型的内部类可以使用。下面给出它们的名称和例子。

    1.静态嵌套类(Static Nested Classes)

    class Outer {   static class Inner {        void go() {         System.out.println("Inner class reference is: " + this);        }   }} public class Test {  public static void main(String[] args) {        Outer.Inner n = new Outer.Inner();      n.go(); }}
    

    输出:Inner class reference is: Outer$Inner@19e7ce87

    2.成员内部类(Member Inner Class)

    成员类是特定于实例的。它可以访问所有方法,字段和外部类本身的引用。

    public class Outer {    private int x = 100;     public void makeInner(){        Inner in = new Inner();        in.seeOuter();    }     class Inner{        public void seeOuter(){            System.out.println("Outer x is " + x);            System.out.println("Inner class reference is " + this);            System.out.println("Outer class reference is " + Outer.this);        }    }     public static void main(String [] args){        Outer o = new Outer();        Inner i = o.new Inner();        i.seeOuter();    }}
    

    输出:

    Outer x is 100
    Inner class reference is Outer$Inner@4dfd9726
    Outer class reference is Outer@43ce67ca

    3.局部方法内部类(Method-Local Inner Classes)

    public class Outer {    private String x = "outer";     public void doStuff() {     class MyInner {         public void seeOuter() {                System.out.println("x is " + x);            }       }       MyInner i = new MyInner();      i.seeOuter();   }   public static void main(String[] args) {        Outer o = new Outer();      o.doStuff();    }}
    

    输出:x is outer

    public class Outer {    private static String x = "static outer";   public static void doStuff() {      class MyInner {         public void seeOuter() {                System.out.println("x is " + x);            }       }       MyInner i = new MyInner();      i.seeOuter();   }   public static void main(String[] args) {        Outer.doStuff();    }}
    

    输出:x is static outer

    4.匿名内部类(Anonymous Inner Classes)

    当您需要给一个GUI应用程序窗口小部件加一个动作监听器时,匿名内部类就会经常被用到。

    button.addActionListener(new ActionListener(){     public void actionPerformed(ActionEvent e){         comp.setText("Button has been clicked");     }});
    

    感谢你看到这里,我是程序员麦冬,一个java开发从业者,深耕行业六年了,每天都会分享java相关技术文章或行业资讯

    欢迎大家关注和转发文章,后期还有福利赠送!

    相关文章

      网友评论

        本文标题:你一定要知道Java中4种类型的内部类

        本文链接:https://www.haomeiwen.com/subject/qerscktx.html