creating a class with class name - java

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?

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.

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.

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
}
}

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.

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

Related

In java I am trying to create an object for a class but it shows an error "The public type Add1 must be defined in its own file" [duplicate]

This question already has answers here:
"The public type <<classname>> must be defined in its own file" error in Eclipse [duplicate]
(8 answers)
Closed 2 years ago.
Here I am getting an error
The public type Add1 must be defined in its own file
in the class name "Add1"
public class Testing_Main
{
public static void main(String[] args)
{
System.out.println("Before Object is Created");
Add1 obj=new Add1();
obj.add1();
System.out.println("After Object is Created");
}
}
public class Add1
{
public int add1()
{
return 5;
}
}
This kind of error The public type className must be defined in its own file occures when we have two public classes in one file. It is a kind of java rule that you should have one public class per file.
Why Only One Public Class Per Source File
According to Java 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 restriction implies that there must be at most one such type per
compilation unit. This restriction makes it easy for a Java compiler
to find a named class within a package. In practice, many programmers
choose to put each class or interface type in its own compilation
unit, whether or not it is public or is referred to by code in other
compilation units.
For example, the source code for a public type wet.sprocket.Toad would
be found in a file Toad.java in the directory wet/sprocket , and the
corresponding object code would be found in the file Toad.class in the
same directory.
To get a more clear picture, let's imagine there are two public classes public class A and public class B in the same source file, and class A has reference to the not-yet-compiled class B. And we are compiling (compiling-linking-loading) class A now while linking to class B the compiler will be forced to check each *.java files within the current package because class B doesn’t have it’s specific B.java file. So, in the above case, it is a bit time consuming for the compiler to find which class lies under which source file and in which class the main method lies.
So the reason behind keeping one public class per source file is to actually make the compilation process faster because it enables a more efficient lookup of source and compiled files during linking. The idea is if you know the name of a class, you know where it should be found for each classpath entry and no indexing will be required.
In java, each class must be associated with its own file. The classes are strictly bound with the filename, so a class called Foo must be places in a file called Foo.java. Therefore, you have to place both the classes TestingMain and Add1 in their own files, namely TestingMain.java and Add1.java respectively.
We cannot have two public classes in one .java file. You can solve this problem by creating a separate file for the class `Add1.
Testing_Main.java
public class Testing_Main
{
public static void main(String[] args)
{
System.out.println("Before Object is Created");
Add1 obj=new Add1();
obj.add1();
System.out.println("After Object is Created");
}
}
Add1.java
public class Add1
{
public int add1()
{
return 5;
}
}
Or If you want to keep Add1 class in Testing_Main, then you can make the Add1 class non-public.

what happens when we have two classes with same names in java?

I have the following files in the same directory.
here is my code
boys.java
import java.io.*;
public class boys
{
String name;
int age;
boys()
{
this.name="empty";
this.age=0;
}
void display()
{
System.out.println("Name =" + name + "\nAge ="+ age );
}
}
girls.java
import java.io.*;
class girls
{
String name;
int age;
girls(String name,int age)
{
this.name=name;
this.age=age;
}
void display()
{
System.out.println("Name="+name+"Age="+age);
}
}
group.java`
import java.io.*;
class boys
{
int rollno;
boys()
{
rollno=100;
System.out.printf("%d",rollno);
}
}
public class group
{
public static void main(String args[])
{
boys b = new boys();
girls g = new girls("sri divya",21);
g.display();
}
}
And here are my question after using the javac command I have only one boys.class file why? and
after the command 'java group' shows me the result of the boys class inside the file group.java and not the boys class inside the file boys.java why?
what should I do if I want output of boys class inside boys.java inspite of having boys class in group.java?
why there is no error inspite of having two same class names?
someone pls help me
And here are my question after using the javac command I have only one
boys.class file why?
There can be only one class named boys in a given package, so the compiler will only generates one.
after the command 'java group' shows me the result of the boys class
inside the file group.java and not the boys class inside the file
boys.java why?
When the compiler parse your group.java file he found two class and then compile them.
what should I do if I want output of boys class inside boys.java
inspite of having boys class in group.java?
Remove the definition of boys from group.java.
why there is no error inspite of having two same class names?
When you compile group.java the compiler found the boys class in it, so it don't need to look outside for its definition.
Defining a class at different places in the same package is a non-sense. Choose.
Now if you really want to replace the boys class with the one generated from the boys.java file you can:
compile group.java (this will generate both group.class and
boys.class from it)
compile boys.java (this will override the old boys.class
with the one of boys.java)
It will work, but I would definitely not use such a construction.
If you name two classes the same, they should be in different packages, and when you want to use both of them in another class, you will have to reference (at least) one of them using its fully qualified name.
If two classes were in the same package with the same name, only one of them would be loaded by the ClassLoader -- which is most certainly not something you would want. This also causes an error in Eclipse, namely: the type Boys is already defined.
So if you can help it, you really should not name the classes the same way (and definitely not in the same package).
Update: I have tested the code, in this exact case the code runs even after throwing the compilation error, the Boys class is loaded by the ClassLoader, the one defined in the Group class is not. Actually, the Boys class in Groups.java is not even in the bytecode, it is removed during compilation.
PS: If you are writing Java code, you really should stick to conventions (upper camelcase classnames, camelcase methods, egyptian brackets etc.), especially if you are not the only one working on the code.

Java class error

chinmay#chinmay-desktop:~$ javac hello.java
hello.java:3: class readnumbers is public, should be declared in a
file named readnumbers.java public class readnumbers
^ 1 error
When I compile any program I get the same error. And now I'm tired of this. Help me out.
Your class name is readnumbers and you have saved it as hello.java
In Java, all public classes (in your case readnumbers) must be contained in a file name same as the class name
Solution - rename file to readnumbers.java OR change the class name to hello
Please note that -
As per Java naming conventions, Java class should start with Capital letter and should follow Camel casing incase of multiple words, for example
Hello
ReadNumbers
What part of the error message do you not understand? It clearly tells you that your class and your java file must have the same name. So either rename your class to hello, or your file to readnumbers.java.
The error says it all.
Your class readnumbers should be declared in a file named
readnumbers.java.
Basically to run a java code you need to write the public class in a file with the same name of the class. For example if your class is A then save it in A.java file.
Java class and filename should be the same. That's why you get this error.
public class readnumbers in file readnumbers.java

Can I compile a java file with a different name than the class?

Is there any way to compile a java program without having the java file name with its base class name.
If so, please explain..
To answer the question take a look at this example:
Create a file Sample.java
class A
{
public static void main(String args[])
{
String str[] = {""};
System.out.println("hi");
B.main(str);
}
}
class B
{
public static void main(String args[])
{
System.out.println("hello");
}
}
now you compile it as javac Sample.java and run as java A then output will be
hi
hello
or you run as java B then output will be hello
Notice that none of the classes are marked public therefore giving them default access. Files without any public classes have no file naming restrictions.
Your Java file name should always reflect the public class defined within that file. Otherwise, you will get a compiler error. For example, test.java:
public class Foo {}
Trying to compile this gives:
[steven#scstop:~]% javac test.java
test.java:1: class Foo is public, should be declared in a file named Foo.java
public class Foo {
^
1 error
So you must have your filename match your public class name, which seems to render your question moot. Either that or I don't understand what you're asking... spending some time explaining what you are actually trying to achieve would go a long way towards asking a more effective question :)
As long as you don't have a public class in your source file, you can name your source file to any name and can compile. But, if you have a public class in your source file, that file should have the name same as your class name. Otherwise, compiler will throw an error.
Example:
Filename: TestFileName.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello,World\n");
}
}
Compiling: javac TestFileName.java
Error:
TestFileName.java:1: class HelloWorld is public, should be declared in a file named HelloWorld.java
public class HelloWorld
^
1 error
No, the public class name must match the file name. Inner, non public, class names may differ.
You must have a public class with the same name as the file name. This is a Very Good Thing. You CAN have secondary classes inside the same file as long as they are not public. They can still be "default" though, so they can still be used by other classes in the same package.
This should not be done for the most part. Java's naming patterns regarding classes and packages are one of the bigger advantages it has--makes a programmers life easier at no cost.
You can use the Java Compile API and compile any java source you wish, the source need not come from a file or could come from a file with an unrelated name. It depends on how obtuse you want to develop your program. ;)
yes, we compile a java file with a different name than the class, provided that there should not be any public class in that file.
If there is any public class in file then in that case you have to give that name as file name. But if your class does not contain any public class then you can give any name to you class.
Please refer below example to make it more clear:
file name : sample.java
class A
{
public static void main(String args[])
{
System.out.println("hi in Class A");
}
}
class B
{
public static void main(String args[])
{
System.out.println("hello in class B");
}
}
then compile it with(windows) : javac sample.java
then run it : java A
output : hi in Class A
then run it : java B
output : hello in class B
Please check and confirm.
It is not necessary to name your file same as the name of the class it has, until this class is public. Though it is a good practice to name the file same as the name of class.
The compiler will compile your file successfully and make a dot class file. Now at the run time you need to give class name to the JVM for that you have to keep the name of the class, which has main method, in your mind. If you keep both the file name and the class name same, it will become easy to remember the name of the compiled dot class file.
for example:
file Dummy.java
class Dummy
{
public static void main(String args[])
{
System.out.println("This is Dummy class running");
}
}
to run the above code we will use :
Javac Dummy.java // to compile
Java Dummy //to run
example:
file Dummy.java
class Diff
{
public static void main(String args[])
{
System.out.println("This is Diff class running");
}
}
to run the above code we will use :
Javac Dummy.java // to compile
Java Diff //to run
I guess what he means is the .java file is named differently than the actual class defined inside it.
I guess this is not possible.
No. You could write a shell script to rename the .java file before compiling it, but javac requires that filenames = class names.
(Also in windows, it's case insensitive, so ASDF.java can compile Asdf.class)
yes, you can choose any name for the file (.java). there is no matter to what are the name of classes in that file means that class names may be totaly different from the file name.
you should compile the program with file name and you should run the program with the class name in which the main method exist.
main methods may be multiple in different classes so you should run it with the class name in which the main method you want to run......
we can save the file tootle different name of class name because in java we compile the program but we run the method.
we have to compile our program with file name and run our class name
Yes,it is possible to compile a java source file with different file name but you need to make sure none of the classes defined inside are public...when you compile the source file the corresponding .class files for the classes inside the source file are created.
Yes,you can save your java source code file with any other name, not same as your main class name but when you comiple it than byte code file name will be same as your main class name. So for your ease of not to memorize to many names for java code run, You need to have your file name same as your main class than only your file name and byte code file will be with same name.
If class is not public you can save it using other name like if classname is Simple then save it Hard.java.
complie->Hard.java
run->Simple.java
Save your java file by .java only.
compile javac .java
run java yourclassname
For example if my program main class name is A then
save by .java only
compile by javac .java
run by java A
yes, we can compile a java file with a different name than the class, provided that there should not be any public class in that file.
If there is any public class in file then in that case you have to give that name as file name. But if your class does not contain any public class then you can give any name to you class.
Please refer below example to make it more clear:
file name : example.java
class A
{
public static void main(String args[])
{
System.out.println("You are in Class A");
}
}
class B
{
public static void main(String args[])
{
System.out.println("You are in class B");
}
}
then compile it with : javac example.java
then run it : java A
output : you are in Class A
then run it : java B
output : you are in class B
Please check and confirm.
You can write more than one main methods in java because java provides main method overloading in which main method can also be overloaded . Once you compile the file here example.java
Compiler create .class file which contains main method when you run the file with java A it will run the A.class file whih contains the main method of class A and that output will be display on you screen ,but when you run this file with java B ,It runs the B.class file which provides main method of B class
So your code is run successfully
Yes. This can be done.
The main reason for the class and file name to be same are to make the job of the complier easy to check which class it needs to run, in the whole list of the Java classes.
So it's a good practice to have filename and class name as same.
And you have compile and run a class with different name other than the filename, If you don't have any public methods in this class.
By convention, the name of the main class should match the name of the file that holds the program. You should also make sure that the capitalization of the filename matches the class name.
The convention that filenames correspond to class names may seem arbitrary. However, this convention makes it easier to maintain and organize your programs. Furthermore, in some cases, it is required.
According to the other answers the only viable solution is to somehow determine the classname from the source, then use it to rename the file to proper name and compile it as usual.
Another option is to alter the package and class name in the source to match file name:
sed -i -r "0,/package/s/^\s*package .*?;/package new.klass.pkg;/" %1
sed -i -r "0,/class/s/public\s+class .+?\{/public class NewClassName {/" %1
Via How to use sed to replace only the first occurrence in a file?
You can have your java file even without name ( simply ".java" ). Only thing is you should not have any public class in your file.

Error when I try to change the class name

class HelloObject {
void speak() {
System.out.println("Hello (from object)!");
}
}
class HelloTester {
public static void main(String[] args) {
HelloObject object = new HelloObject();
object.speak();
}
}
When I change the "HelloTester" class name to something like "HelloTester2", the program suddenly works. The class file is called ClassesBegin.java.
Why does the java program not work when I try to change the name of the class?
EDIT: Sorry I should have clarified more. I changed the class name to HelloTestera and this is the error I get:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloTester
But it works even when the file name has nothing to do with a class name. It works with HelloTester when the file name is ClassesBegin.java
You need to change the file name, not just the class name.
In Java, the .java and .class names have to be identical to the class name.
Hence, each class has to go to a separate file with its name so that a separate .class file is created.
Putting two different classes in the same file is a C++ practice that works with its compilation model, not with Java.
Edit: User ended up clarifying what caused his error, so obviously my answer here is not relevant. All the above applies to public classes. You can pull that off for package-level classes though I have to say that I consider that a horrible practice. If you're going to have something used by multiple classes in your package, give it its own file. If it's used just by one class, make it an inner class...
"EDIT: Sorry I should have clarified more. I changed the class name to HelloTestera and this is the error I get: Exception in thread "main" java.lang.NoClassDefFoundError: HelloTester But it works even when the file name has nothing to do with a class name. It works with HelloTester when the file name is ClassesBegin.java"
The file name and the class name must match if the class is public.
If you chagned the class name to "HelloTestera" but ran "java HelloTester" (which is what java.lang.NoClassDefFoundError: HelloTester would indicate) then the issue is that you passed the wrong class name to "java".
But save yourself a lot of time and name the class and the file the same thing and keep it at one top level class per file. A simple way to "force" that is to make all of your classes public for now (you can only have one public class per file). This will really save you from making some mistakes.
You are allowed to have as many non-public classes in your ClassesBegin file as you like in terms of compilation. But only the public (ClassesBegin in this case; until you change the name of the file) is able to be used externally.
In particular, the main() method must be public, and in a public class to be able to be found by java. Rename your file to HelloTester to make it work.
Or - rename the HelloTester class in your IDE, which probably is relaming the file automatically, since it has a main method, and the IDE knows that it needs to be the public class...
The easiest way to do this is:
1) only one top level class per file
2) the name of the class and the name of the file must match (name and CasE)
This makes it easier to find you classes (the name of the class is the name of the file) and you don't wind up with some odd issues where the compielr cannot find all of the classes to copmpile.
Java also has a restriction where the name of a public class 100% must be the same as the name of the file. The restriction is only on public classes (or interfaces or enums). You can have as many non-public types as you want in a file... but don't do that - stick with one top level class/interface/enum per file.
You write:
I changed the class name to HelloTestera and this is the error I get: Exception in thread "main" java.lang.NoClassDefFoundError: HelloTester
It seems you are not actually running the renamed class but the old one. Did you call Java with the new changed class name? Did you recompile the file before running the class?
After renaming the class, you should first run:
javac ClassesBegin.java
And then:
java HelloTestera
Which for me yields:
Hello (from object)!
Usually, when using an IDE, these issues are handled for you (compile before running).

Categories