Java--内部类

Java–内部类

package com.zy.oop;

/**
 *description: Java--内部类
 *@program: 基础语法
 *@author: zy
 *@create: 2023-02-22 22:40
 */
public class Outer {

    private int id;
    public void out(){
        /*Inner inner = new Inner();
        inner.in();*/
        System.out.println("这是外部类的方法");
    }

    // 一个项目应该只存在一个main方法
    public static void main(String[] args) {

        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.in();
        inner.getId();
        System.out.println("========================");
        Outer.Inner2.in();
        System.out.println("========================");
        outer.methodClass();
        System.out.println("========================");
        // 没有名字初始化类,不用将实例保存到变量中,引申出匿名内部类
        new Outer2().out();
        System.out.println("========================");
        HelloService helloService = new HelloService() {
            @Override
            public void hello() {
                System.out.println("匿名内部类说你好");
            }
        };
        helloService.hello();

    }

    public void methodClass(){
        /**
         * @Description 局部内部类
         * @author zy
         * @date 2023-2-22 22:56
         */
        class Inner3 {
            public void in(){
                out();
                System.out.println("这是局部内部类的方法");
            }
        }

        Inner3 inner3 = new Inner3();
        inner3.in();
    }

    /**
     * @Description 成员内部类:通过外部类实例化内部类
     * @author zy
     * @date 2023-2-22 22:44
     */
    class Inner {
        public void in(){
            out();
            System.out.println("这是成员内部类的方法");
        }

        // 获得外部类的私有属性
        public int getId(){
            return id = 10;
        }
    }

    /**
     * @Description 静态内部类
     * @author zy
     * @date 2023-2-22 22:50
     */
    static class Inner2 {
        public static void in(){
            //out(); // 无法直接调用外部类方法,除非其是静态的
            System.out.println("这是静态内部类的方法");
        }

        // 无法直接获得外部类的私有属性,除非该属性是静态的
        public int getId(){
            return 0; //id = 10;
        }
    }
}

/**
 * @Description
 * 一个Java类中可以有多个class类,但只能有一个public修饰的类
 * @author zy
 * @date 2023-2-22 22:54
 */
class Outer2 {
    public void out(){
        System.out.println("这是外部类2的方法");
    }
}

interface HelloService {
    void hello();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值