Thursday, March 24, 2011

Defining classes in Java files

I have found one error in my Java program:

The public type abc class must be defined in its own class

How can I resolve this error? I am using Eclipse. I am new to Java programming.

From stackoverflow
  • A public class with the name of "abc" must be in a file called abc.java

  • Each source file must contain only one public class. A class named ClassName should be in a file named ClassName.java, and only that class should be defined there.

    Exceptions to this are anonymous and inner classes, but understanding you are a beginner to Java, that is an advanced topic. For now, keep one class per file.

    Answering your addition: it is OK to inherit classes and that's totally fine. This does not matter, each class should still have its own file.

    Jon Skeet : You can have multiple top-level classes in the same file, but only one *public* class. Only public classes have to conform to the filename rule (in terms of javac and Eclipse behaviour; a compiler could enforce this for non-public types - see spec reference above).
  • Public top-level classes (i.e. public classes which aren't nested within other classes) have to be defined in a file which matches the classname. So the code for class "Foo" must live in "Foo.java".

    From the language specification, section 7.6:


    When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

    • The type is referred to by code in other compilation units of the package in which the type is declared.

    • The type is declared public (and therefore is potentially accessible from code in other packages).


    This rule, which doesn't have to be followed by compilers, is pretty much universally adhered to.

  • Ok, maybe an example will help.

    In file MySuperClass.java:

    public class MySuperClass {
        // whatever goes here
    }
    public class MySubClass1 extends MySuperClass {
        // compile error: public class MySubClass1 should be in MySubClass1.java
    }
    class MySubClass2 extends MySuperClass {
        // no problem (non-public class does not have to be in a file of the same name)
    }
    

    In file MySubClass3.java:

    public class MySubClass3 extends MySuperClass {
        // no problem (public class in file of the same name)
    }
    

    Does that make things clearer?

  • You can create a new class an a existing file if it's private, but you should not do this.

    Create one file per class. Eclipse does that for you, if you create a new class.

    For programming Java, you have to understand the construct of classes, packages and files. Even if Eclipse helps you, you have to know it for yourself. So start reading Java books or tutorials!

0 comments:

Post a Comment