为什么在java中的一个文件中不能定义两个公共类? [英] Why can't two public classes be defined in one file in java?

查看:403
本文介绍了为什么在java中的一个文件中不能定义两个公共类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么B类不能公开?
我如何在其他类中使用类?是否最好在Cons?里面定义它?!

Why Class B can't become public? How can I use class be in other classes? Is it better to define it inside Cons?!

   //    public class B { why not?

   class B {
        int x;  
        B (int n) {
            x=n;
            System.out.println("constructor 'B (int n)' called!");
        }
    }

    public class Cons { 
        public static void main(String[] args) {B b = new B();}
    }


推荐答案

根据java语言规范,文件中的一个公共类(.java)和文件名应与公共类名相同。

As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name.

如果您希望B类在其他plac中可访问,单独的B.java文件并将您的B类代码移动到该文件。

If you want class B accessible in other placs, you may create a separate B.java file and move your Class B code to that file.

线程可能会给你一些更多的信息。

This thread may give you some more information.

这篇关于为什么在java中的一个文件中不能定义两个公共类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆