| Author |
Files with no public classes can have a name that does not match any of the classes in the file
|
Niharika Gottipati
Ranch Hand
Joined: Mar 03, 2013
Posts: 30
|
|
Hi, I am lil confused with the statement
"Files with no public classes can have a name that does not match any of the classes in the file".
To test this, I created a java class - One.java with the following code :
class Onetwo {
void method1(){
System.out.println("Hi neeha");
}
}
I can see a Onetwo.class file, which makes sense and guess that's the reason why I am getting the below error :
java.lang.NoClassDefFoundError: One
Caused by: java.lang.ClassNotFoundException: One
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Exception in thread "main"
So my question is, how can we have a class which doesn't have any method with the class name ??
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26195
|
|
Niharika,
Welcome to CodeRanch!
The code compiles just fine which is what that statement refers to. It doesn't run because the code isn't public and the Java runtime doesn't have access to it. It's legitimate to have a class without a main method though.
ANd of course in the real world, you wouldn't do this because it is confusing and hard to maintain.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Niharika Gottipati
Ranch Hand
Joined: Mar 03, 2013
Posts: 30
|
|
Thanks Jeanne,
That makes some sense. It means it builds the .class file but doesn't run because it doesn't have any public class which means it doesn't have any code to run.
But if I can run the code without main method I guess I can do it with static block only. Is there another way of doing this?
|
 |
 |
|
|
subject: Files with no public classes can have a name that does not match any of the classes in the file
|
|
|