Reputation:
I am a beginner in Java. Could anyone please help me understand the following concept?
What I have done here is I tried to create a class as Sample
, which I mentioned below, where I am printing You are in Main Method
class Sample
{
public static void main(String args[]) {
System.out.println("You are in Main Method");
}
}
and saved this java file as Student.java.
I didn't get any error in Eclipse.
Now, I had specified a public
in front of this class as public class Sample
and I am getting an error.
Could anyone please clarify for me with the right answer, as I am finding this to be difficult to understand?
Upvotes: 0
Views: 265
Reputation: 1
first u read visibility of modifies i think u r well understanding ur problem
Access Modifiers
Same Class Same Package Subclass Other packages
public Y Y Y Y protected Y Y Y N no access modifier Y Y N N private Y N N N
Upvotes: 0
Reputation: 3669
Public classes must have their own compilation units (i.e. .java
files which must match the class name) and are compiled into ClassName.class
files.
This way the JDK knows where it should generate the output .class
files and the JVM know where to load the .class
files from.
An exception to this would be inner/nested classes which do not require a separate file and that get their byte code generated into files like OuterClassName#InnerClassName.class
. Inner classes are stored in the same .java
file as the outer class that defines them.
Note:ClassName
, OuterClassName
and InnerClassName
are the names of the classes defined by you.
Upvotes: 0
Reputation: 363667
All public class must be saved with the same name. So if you have class named Sample it has to be saved in file named Sample.java
If you use a package, you have to save file in this folder. Example com.example, you have to save Sample.java in a folder root/com/example.
package com.example;
public class Sample{
public static void main(String[] args){
// put here your code
}
}
Upvotes: 0
Reputation: 3381
Ensure that the class name is equal to the file name appended with ".java". So if you name your class Sample
then the file should be named Sample.java
. This is why you're getting the error because your class name is different to what you have named the file.
For future references, when you're getting a compiler error/run time error, whatever, please ensure that you list the error here. It makes it a lot easier to deal with the problem, and the chances that you will get an answer that actually solves your problem increases.
Upvotes: 0
Reputation: 3863
In Java all classes with scope public
must be save in file which name is exactly the same like name of this class. So if you have class named Sample
it has to be saved in file named Sample.java
. If class is named Student
then file should be named Student.java
One of reason for this is that packages
named and class
names can be easly mapped to real system paths.
Upvotes: 4