外部类与内部类

什么是外部类、内部类

public class Outer {
class Inner{

}
}

如上述代码,Outer是一个外部类,Inner是一个内部类,内部类也可以用public、static等修饰,但要注意:

1.静态内部类中可以有非静态的方法;
2.当内部类中有静态方法或者静态成员变量时,一定是静态内部类。

外部类与内部类的区别与联系:
内部类可以访问外部类所有的方法和属性,如果内部类和外部类有相同的成员方法和成员属性,内部类的成员方法调用要优先于外部类即内部类的优先级比较高(只限于类内部,在主方法内,内部类对象不能访问外部类的成员方法和成员属性),外部类只能访问内部类的静态常量或者通过创建内部类来访问内部类的成员属性和方法。

如何访问
1. 外部类访问内部类:
内部类被static修饰:可以直接new Inner in = new Inner();
内部类没有被static修饰:先new出外部类的实例,再new内部类的 Inner in = new Outer().new Inner();
2. 内部类访问外部类:(外部类.this.变量)

下面有一个例子很好的展示了内部类与外部类的访问:

 

复制代码
public class Outer {
    int x = 9;
    class Inner{
        int x = 8;
        public void test(){
            int x = 7;
            System.out.println(x);
            System.out.println(this.x);
            System.out.println(Outer.this.x); //这里展示了三种不同的访问及其对应的结果
            test1();
        }
    }

    private void test1(){
        System.out.println("test");
    }
    public static void main(String[] args) {
        Inner in = new Outer().new Inner();
        in.test();
    }
}
复制代码

输出结果:7,9,8,test

3. 在外部类中访问另一个外部类中的类
我们只需从外部类一直点到内部类即可:Father.Child outting = new Father().new Child();。
下面有个例子展示了这一过程:

 

复制代码
class Father {  //外部类
    String name = "zhangjun";

    class Child {  //内部类
        public void introFather() {
            System.out.println(Father.this.name);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Father.Child outting = new Father().new Child();
        outting.introFather();  //调用introFather
    }
}
复制代码

-输出:zhangjun

注意:

一般只需将有main方法的类用public修饰,否则会提示错误: 类 XXX 是公共的, 应在名为 XXX.java 的文件中声明,当然你也可以去整一个新的.java;
编译时只需编译main方法所在的类,其它类会根据你的访问自动完成编译。
————————————————
版权声明:本文为CSDN博主「Mason_Swift」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Moum_j/article/details/123785552

posted on   天军  阅读(157)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示