aarya
aarya

Reputation:

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.

Upvotes: 4

Views: 7023

Answers (5)

Yuval Adam
Yuval Adam

Reputation: 165340

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.

Upvotes: 9

guerda
guerda

Reputation: 24069

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!

Upvotes: 1

Michael Myers
Michael Myers

Reputation: 192055

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?

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1503799

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.

Upvotes: 6

krosenvold
krosenvold

Reputation: 77251

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

Upvotes: 5

Related Questions