package MainCon;

public interface Animal {
void voice();
}

class Dog implements Animal {
public void voice() {
System.out.println("W W!");
}
}
class cat implements Animal{
public void voice(){
System.out.println("M M!");
}
}
class pig implements Animal{
public void voice(){
System.out.println("GU LI");
}
}
class Store {
public static Animal get(String choice){
if(choice.equalsIgnoreCase("dog")){
return new Dog();
}else if(choice.equalsIgnoreCase("pig")){
return new Dog();
}else{
return new cat();
}
}
}
public class AnimalTest{
public static void main(String[]args){
Animal a1 = Store.get("dog");

a1.voice();

Animal a2 = Store.get("pig");

a2.voice();
}
}AnimalTest类报错、
The public type AnimalTest must be defined in its own file-----------------------------
我是个新学的菜鸟,撒都不懂,希望高手指点下。万分感谢!

解决方案 »

  1.   

    public interface Animal  改成  interface Animal
    同一个文件中只能有一个public类
      

  2.   

    程序没错···是AnimalTest要放到另外一个文件的意思!! 
      

  3.   

     interface Animal {
            void voice();
        }
        
        class Dog implements Animal {
            public void voice() {
                System.out.println("W W!");
            }
        }
        class cat implements Animal{
            public void voice(){
                System.out.println("M M!");
            }
        }
        class pig implements Animal{
            public void voice(){
                System.out.println("GU LI");
            }
        }
        class Store {
            public static Animal get(String choice){
                if(choice.equalsIgnoreCase("dog")){
                    return new Dog();
                }else if(choice.equalsIgnoreCase("pig")){
                    return new Dog();
                }else{
                    return new cat();
                }
            }
        }
        public class AnimalTest{
            public static void main(String[]args){
                Animal a1 = Store.get("dog");
                
                a1.voice();
                
                Animal a2 = Store.get("pig");
                
                a2.voice();
            }
        }
    代码已经帮你改好 输出
    W W!
    W W!接口是不能用来定义的 
      

  4.   


    我用你的代码 还是报错【你的是把上面定义接口的public去掉保留下方public】
    The public type AnimalTest must be defined in its own file
    于是我把2个public都去掉了,结果OK了。
    还是谢谢你。
      

  5.   

    可比把public interface Animal  改成  interface Animal
    或者把public interface Animal放到另一个文件中.
      

  6.   

    除了applet之外都只能有一个,applet没有public也行
      

  7.   

    楼主没用IDE工具?这种问题就是以下几中原因:
    - 一个文件中有多个public的class
    - 文件名和public的class类名不一致
    - 是否用的内部类,还是多个类放到一个文件中不符合规则
    ......