java中的文件名和类名不同
我创建了一个名为In.java的文件,输入以下代码
class In { int a; public static void main( String args[] ) { Inheritance h = new Inheritance(); h.set( 6 ); System.out.println( h.get() ); } void set( int a ) { this.a = a; } int get() { System.out.println( a ); return a; } }
编译时,它向我显示了有关inheritance的错误。 然后我重命名为In as I Inheritance
class Inheritance { int a; public static void main( String args[] ) { Inheritance h = new Inheritance(); h.set( 6 ); System.out.println( h.get() ); } void set( int a ) { this.a = a; } int get() { System.out.println( a ); return a; } }
现在当我编译它时编译并创建了Inheritance.class,但是当我编译为public class Inheritance
时,文件名仍然是In.java,它提醒我应该将类更改为Inheritance.java。 现在当我运行java In
它显示错误为Error: Could not find or load main class In
现在我再次将该类重命名为In as
class In { int a; public static void main( String args[] ) { Inheritance h = new Inheritance(); h.set( 6 ); System.out.println( h.get() ); } void set( int a ) { this.a = a; } int get() { System.out.println( a ); return a; } }
现在,当我编译它编译为In.class时,当我运行输出它运行程序显示
6 6
当我用In.java创建程序并运行名为Class Inheritance的类时,它编译并给出了Inheritance.class。 1.如果类名和文件名不同,编译器是否会显示错误? 2.当我运行java In
它显示Error: Could not find or load main class In
生成In.class文件为什么在编译带有类名作为inheritance的In.java时它没有检测到它? 那么一个类文件可以在同一目录中使用任何其他类文件吗?
任何声明为public
类都应保存在同名文件中。 如果公共类的名称和包含它的文件不同,则会出现编译错误。 未声明为public
可以保存在不同名称的文件中。
请注意,生成的类文件以java类命名,而不是文件名。 请看下面的例子。
在下面的插图中, X
是任何有效名称( Foo
和Bar
除外)。
例1:
// filename X.java (doesn't compile) public class Foo { } public class Bar { }
编译器抱怨公共类Foo
和Bar
没有出现在他们自己的.java
文件中。
例2:
// filename Foo.java (doesn't compile) public class Foo { } public class Bar { }
错误与上述相同,但这次只适用于Bar
。
例3:
// filename Foo.java (compiles) public class Foo { } class Bar { }
生成的文件是Foo.class
和Bar.class
。
例4:
// filename X.java (compiles) class Foo { } class Bar { }
生成的文件是Foo.class
和Bar.class
。