栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础(内部类)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础(内部类)

内部类:定义在类里的类

        成员内部类

        局部内部类

        静态内部类

        匿名内部类

// 成员内部类

public class Demo01{
    public static void main(String[] args){
        Outer outer = new Outer();
        //通过外部类对象创建内部类对象
        Outer.Inner inner = outer.new Inner();
        inner.setId(20);
        System.out.println(inner.getId()); 
    }
}

public class Outer {
    //成员属性
    public int num = 1;

    //成员内部类
    public class Inner{
        private int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }
}
//        局部内部类:作用域只在方法
public class Demo02{
    public static void main(String[] args){
        Outer outer = new Outer();
        outer.method01();
    }
}

public class Outer{
    public void method01{
        class Inner{
            private int id;
            
            public void setId(int id){
                this.id = id;
            }
            public int getId(){
                return id;
            }
        }
        Inner inner = new Inner();
        inner.setId(10);
    }
}
//        静态内部类
public class Demo03 {
    public static void main(String[] args) {
        Outer.Inner inner = new Outer.Inner();
        inner.setId(10);
        System.out.println("内部类属性:"+inner.getId());
    }
}

public class Outer {
    //静态属性
    public static int num;

    //静态内部类
    public static class Inner{
        private int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }
}
//        匿名内部类
//           减少了类的创建,只适用于对象的方法只调用一次或者少次

public class Demo04{
    Test test = new Test();
    test.method();
    
    System.out.println("---使用多态---");
    MyInterface myInterface = new Test();
    myInterface.method();

    System.out.println("---使用匿名内部类---");
    MyInterface2 myInterface2 = new MyInterface(){
        @Override
        public void method02() {
            System.out.println("匿名内部类创建的方法");
        }
    };
    myInterface2.method02();
}

//        Test类
public class Test implements MyInterface {
    @Override
    public void method() {
        System.out.println("实现接口重写的方法");
    }
}

//        接口类1
public interface MyInterface {
    void method();
}

//        接口类2
public interface MyInterface2 {
    void method02();
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/460155.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号