wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Files with no public classes can have a name that does not match any of the classes in the file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Files with no public classes can have a name that does not match any of the classes in the file" Watch "Files with no public classes can have a name that does not match any of the classes in the file" New topic
Author

Files with no public classes can have a name that does not match any of the classes in the file

hari gutta
Ranch Hand

Joined: Mar 03, 2013
Posts: 33
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
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30586
    
154

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
hari gutta
Ranch Hand

Joined: Mar 03, 2013
Posts: 33
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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Files with no public classes can have a name that does not match any of the classes in the file