java 静态外部类,为什么外部类在Java中不是静态的?

本文探讨了Java中外部类和内部类的特性。外部类可以是public, final, default或abstract,但不能是static,因为静态类在Java中用于创建没有实例的类,而内部类则隐含地持有对外部类的引用,允许直接访问外部类的成员。文章通过示例解释了静态与非静态内部类的区别,并强调了在外部类中不适用静态修饰的原因。
摘要由CSDN通过智能技术生成

In java, An outer class may be public, final, default or abstract.

Why not Static like

public static class MyClass{}

解决方案

An outer class is already implicitly static.

Non-static nested class (= inner class) means thats the inner class implicitly has a reference to its parent class.

That's why, for nested class, you can distinguish between static and non-static. This does not make sense for outer classes.

Here is an example to understand the difference between static/non-static nested class. You should understand why it does not make sense in an outer class.

public class MyClass {

private String anAttributeOfMyClass;

private /*static*/ class MyInnerClass {

public void foo() {

/*

* Here, I can access the attribute of the parent class

* because I implicitly have a reference to it.

* Try to make the nested class static an see the difference.

*/

anAttributeOfMyClass.trim();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值