美文网首页
java内部类的分类

java内部类的分类

作者: 7i昂 | 来源:发表于2019-08-15 18:08 被阅读0次

    一、静态内部类

    public class Out {
        private static String name;
        private int age;
    
        public static class In{
            private int age;
            public void sayHello(){
                
                System.out.println("my name is : "+name);
                //--编译报错---
                //System.out.println("my age is :"+ age);
            }
        }
    }
    public static void main(String [] args){
        Out.In innerClass = new Out.In();
        innerClass.sayHello();
    }
    

    二、成员内部类

    public class Out {
        private String name;
    
        public void showName(){
            System.out.println("my name is : "+name);
        }
    
        public class In{
            public void sayHello(){
                System.out.println(name);
                Out.this.showName();
            }
        }
    }
    public static void main(String [] args){
        Out out = new Out();
        Out.In in = out.new In();
        in.sayHello();
    }
    

    三、方法内部类

    public class Out {
        private String name;
    
        public void sayHello(){
            class In{
                public void showName(){
                    System.out.println("my name is : "+name);
                }
            }
    
            In in = new In();
            in.showName();
        }
    }
    

    四、匿名内部类

    //首先定义一个普通类
    public class Out {
        private String name;
    
        private void sayHello(){
            System.out.println("my name is :" + name);
        }
    }
    
    //定义和使用一个匿名内部类
    public static void main(String [] args){
        Out out = new Out(){
            @Override
            public void sayHello(){
                System.out.println("my name is cyy");
            }
            public void showName(){
                System.out.println("hello single");
            }
        };
        out.sayHello();
    }
    
    

    相关文章

      网友评论

          本文标题:java内部类的分类

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