今天我在调试一个java程序时出错,出现提示class CountInstances is public,should be declared in a file named CountInstances.java;
并且显示指出public class CountInstances中的class出错,请问这是什么问题?
源代码如下:
    public class CountInstances{
    private static int numInstances =0;
    protected static int getNumInstances(){
        return numInstances;
    }
    private static void addInstance(){
        numInstances++;
    }
    CountInstances(){
        CountInstances.addInstance();
    }
    public static void main(String arguments []){
        System.out.println("Starting with "+CountInstances.getNumInstances()+" instances");
        for(int i=0;i<10;++i)
            new CountInstances();
        System.out.println("Created"+CountInstances.getNumInstances()+" instances");
    }
}

解决方案 »

  1.   

    这个类所在的文件名要是CountInstances.java
      

  2.   

    貌似在我这里编译运行正常
    Starting with 0 instances
    Created10 instances
    这是输出结果
      

  3.   

    文件的名字要和文件中的public class类名相同。
      

  4.   

    出现提示class CountInstances is public,should be declared in a file named CountInstances.java; 
    一楼的对,可能原因是你的源文件名和你的源文件里的修饰为public的类名相同
      

  5.   

    两种情况:一 如果你的类的名称是CountInstances,我在eclipse运行了,可以正常的运行,结果是
       Starting with 0 instances
       Created10 instances
    二 如果类的名称定义的不是CountInstances,如果是在eclipse下面编辑,编辑器马上就会报错的,报错如下:
       Multiple ers at this line
    - The public type ss must be defined in its own file
    - The public type y must be defined in its own file
       如果使用的是记事本或者其他编写的,在dos命令行运行的话就会报错,还有就是要制定包路径