java 类同名,为什么Java文件必须与其公共类同名?

本文讨论了Java中类的访问权限与其文件名的关系。第一种情况,类未声明为public,属于包私有,仅同包内可访问,能正常编译。第二种情况,类声明为public,根据Java的编译规则,公共类必须与文件名相同,否则会导致编译错误。这种限制确保了类的可查找性,便于编译器和虚拟机定位。
摘要由CSDN通过智能技术生成

I have one file named temp.java. I wrote the following code. Why does this work?

class demo //not public keyword and not same as filename

{

public static void main(String []args)

{

System.out.println("this is Main method");

}

}

Any why does this not work?

public class demo

{

public static void main(String []args)

{

System.out.println("this is Main method");

}

}

解决方案

In your first example, your class is actually declared as "package private" (no modifiers), which means only classes within the same package can access it. In your second example, you have declared it as public.

This is a scenario where the compiler has met the JLS quite well.

When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

The type is referred to by code in other compilation units of the package in which the type is declared.

The type is declared public (and therefore is potentially accessible from code in other packages).

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

What this means is, for scenario 1, that because you only have temp.java with package private class demo, it is not being referred to by code in any other compilation units of the package, therefore it will compile without issue.

Your second scenario has declared the class public - which means it is potentially accessible from code in other packages - so it has to conform to the standards that the class name equals the file name.

If you created another class in your first scenario (within the same package) and then tried to reference the class demo, you should get a compilation error.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值