• 周五. 4月 26th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

java中的内部类

admin

11月 28, 2021

内部类就是在一个类的内部定义一个类,比如:A类中定义一个B类,那么B类相对A类来说就称为内部类,而A类相对B类来说就是外部类啦。

【示例 1】成员内部类

class Outer {
    private int num = 10;
    
    public void out() {
        System.out.println("这是外部的方法");
    }

    class Inner {
        public void in() {
            System.out.println("这是内部的方法");
        }

        public void getNum() {
            System.out.println(num);
        }
    }
}

public class Test2 {
    public static void main(String[] args) {
        Outer outer = new Outer();
        //通过外部类来实例化内部类
        Outer.Inner inner = outer.new Inner();
        inner.in();
        inner.getNum();
    }
}

执行结果如下:
image

【示例 2】局部内部类

class Outer1 {
    //局部内部类
    public void method() {
        class Inner {
            public void in() {
                System.out.println("我是局部内部类");
            }
        }
        new Inner().in();
    }
}

public class Test3 {
    public static void main(String[] args) {
        Outer1 outer1 = new Outer1();
        outer1.method();
    }
}

执行结果如下:
image

【示例 3】静态内部类

class Outer2{
    private int num = 100;
    public void out(){
        System.out.println("我是外部类");
    }

    //静态内部类
    static class Inner2{
        public void in(){
            System.out.println("我是内部类");
        }
    }
}

public class Test4 {
    public static void main(String[] args) {
        Outer2 outer2 = new Outer2();
        outer2.out();

        Outer2.Inner2 inner2 = new Outer2.Inner2();
        inner2.in();
    }
}

执行结果如下:
image

【示例 4】匿名内部类

class Xxx {
    public void shout() {
        System.out.println("嗷~");
    }
}

interface UserService {
    void hello();
}

public class Test5 {
    public static void main(String[] args) {
        //匿名对象.方法
        new Xxx().shout();

        // 适合那种只需要使用一次的类。比如:键盘监听操作等等。
        new UserService() {
            @Override
            public void hello() {
                System.out.println("hello");
            }
        }.hello();
    }
}

执行结果如下:
image

《java中的内部类》有一个想法
  1. EndoPump is a dietary supplement for men’s health. This supplement is said to improve the strength and stamina required by your body to perform various physical tasks. Because the supplement addresses issues associated with aging, it also provides support for a variety of other age-related issues that may affect the body. https://endopumpbuynow.us/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注