1
public interface Shape { } 
class Circle implements Shape { 
    Circle(int radius) { /* ... */ } 
} 
class Rectangle implements Shape { 
    Rectangle(int height, int width) { /* ... */ } 
} 
public class Main { 
    public static void main (String[] args) { 
        Shape[] shapes = new Shape[2]; 
        shapes[0] = new Circle(1); 
        shapes[1] = new Rectangle(1, 2); 
        writeShapes(shapes); 
    } 
    public static void writeShapes(Shape[] shapes){ 
        for(Shape shape:shapes){ 
            if(shape instanceof Circle) System.out.println("Circle"); 
            else if(shape instanceof Rectangle) System.out.println("Rectangle"); 
        } 
    } 

In the example, I want to add new shape. However, I could not get the point what's going on about the error "The public type Main must be defined in its own file" which occurs on my main method. I have tried to add "static" in front of main, but it does not work! Any suggestions are appreciated!

史超南
  • 67
  • 2
  • 8
  • 5
    A Java file may only contain one public class or interface. As general rule, you separate all those interfaces and classes into separate files ... unless you want to use inner classes, but that's another question – MadProgrammer Oct 01 '18 at 06:11
  • @Deadpool First, you need to understand by what I mean as ["inner class"](https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html) and they most certainly can be `public`, they can even be `static` allowing them to be created out side of an instance of the parent class – MadProgrammer Oct 01 '18 at 06:21
  • @MadProgrammer More specifically, only one *top-level* type. – chrylis -cautiouslyoptimistic- Oct 01 '18 at 06:42

2 Answers2

2

A .java file can contain only one public class/interface.

In your case, you can either move the Main class or Shape interface to another file.

Rishikesh Dhokare
  • 3,559
  • 23
  • 34
0

A .java file can only have one public class/ interface. So you might want to move one of the classes out of the file. You can still, however, call it in the main class using object variables.

Since you are not using any actionListeners, then inner classes don't make sense and are not useful.