• 匿名对象,内部类


    1   匿名对象的概念

    创建一个匿名对象

    new Person();

    l  创建匿名对象直接使用,没有变量名。

    l  匿名对象在没有指定其引用变量时,只能使用一次。

    l  匿名对象可以作为方法接收的参数、方法返回值使用。

    2   内部类概念

    1.成员内部类:

    l  定义格式

    class 外部类 {

        修饰符 class 内部类 {

            //其他代码

    }

    }

    l  访问方式

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

    public class Outer {
        private int a=0;
        //成员内部类
        class Inter{
            private int a=1;
            public void aa(){
                 int a=2;
                 System.out.println(a);
                 System.out.println(this.a);
                 System.out.println(Outer.this.a);
            }
        }
    }
    
    public class Demo {
        public static void main(String[] args) {
            //创建成员内部类对象的方式
            //外部类    .内部类 变量名=new 外部类().new 内部类();
            Outer.Inter in=new Outer().new Inter();
            in.aa();
        }
    }

    2.局部内部类:

    l  定义格式

    class 外部类 {

        修饰符 返回值类型 方法名(参数) {

    class 内部类 {

    //其他代码

    }

    }

    }

    l  访问方式

    在外部类方法中,创建内部类对象,进行访问。

    public class Outer {
        public void method(){
            class Inner{
                public void in(){
                    System.out.println("局部内部类方法");
                }
            }
            Inner in=new Inner();
            in.in();
        }
    }
    
    public class Demo {
        public static void main(String[] args) {
            Outer out=new Outer();
            out.method();
        }
    }

    3    匿名内部类概念

    格式:

    new 父类或接口(){

        //进行方法重写

    };

    public interface Smoking {
        public abstract void smoke();
    }
    
    public class Test {
        public static void main(String[] args) {
            Student s=new Student();
            s.smoke();
            //匿名内部类
            new Smoking(){
                public void smoke(){
                    System.out.println("男人抽烟");
                }
            }.smoke();
        }
        
    }
  • 相关阅读:
    SVG前戏—让你的View多姿多彩
    分享几个Android很强势的的开源框架
    终于,我还是下决心学Java后台了
    金9银10,分享几个重要的Android面试题
    django-多表操作2
    python基础-文件操作
    django-单表操作
    django-多表操作
    django-模板层基础2
    djano-模板层基础知识
  • 原文地址:https://www.cnblogs.com/quanjunkang/p/10616783.html
Copyright © 2020-2023  润新知