Java内部类Demo

  1. 接口

package com.chaitc.innerClassDemo;

/**
 * ClassName: Ball
 * Package: com.chaitc.innerClassDemo
 * Description:
 *
 * @Author: chaitc
 * @Create: 2023/1/22 -12:45
 * @Version: v1.0
 */
public interface Ball {
    void play();
}
  1. Test

package com.chaitc.classDemoTest;

import com.chaitc.innerClassDemo.Ball;

/**
 * ClassName: BallTest
 * Package: com.chaitc.classDemoTest
 * Description:
 *
 * @Author: chaitc
 * @Create: 2023/1/22 -12:45
 * @Version: v1.0
 */
public class BallTest {
    void playBall(Ball ball) {
        ball.play();
    }

    /**
     * 方法内部类
     * @return 返回创建的类实例对象
     */
    public Object info() {
        class Inner_f implements Ball {

            @Override
            public void play() {
                System.out.println("*****************");
                System.out.println("方法内部类:");
                System.out.println("打乒乓球");
            }
        }
        return new Inner_f();
    }
    // 成员内部类
    class Inner_m implements Ball {

        @Override
        public void play() {
            System.out.println("成员内部类:");
            System.out.println("打篮球");
        }
    }

    static class Inner_n implements Ball {

        @Override
        public void play() {
            System.out.println("静态内部类:");
            System.out.println("打羽毛球");
        }
    }

    public static void main(String[] args) {
        BallTest ballTest = new BallTest();
        BallTest.Inner_m inner_m = ballTest.new Inner_m();
        ballTest.playBall(inner_m);
        System.out.println("===========================");

        ballTest.playBall((Ball) ballTest.info());
        Ball ball = new Ball() {
            @Override
            public void play() {
                System.out.println("*****************");
                System.out.println("匿名内部类:");
                System.out.println("打排球");
            }
        };
        System.out.println("===========================");
        ballTest.playBall(ball);
        System.out.println("===========================");
        // 获取静态内部类实例对象
        BallTest.Inner_n inner_n = new BallTest.Inner_n();
        ballTest.playBall(inner_n);
    }
}
  1. 输出结果:

成员内部类:
打篮球
===========================
*****************
方法内部类:
打乒乓球
===========================
*****************
匿名内部类:
打排球
===========================
静态内部类:
打羽毛球

Process finished with exit code 0

你可能感兴趣的:(java开发,java,开发语言)