• Post Reply Bookmark Topic Watch Topic
  • New Topic

NoClassDefFoundError with multiple packages  RSS feed

 
achuthan mukundarajan
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am preparing for SCJP and wanted to try out accessing a protected variable from a subclass which is in a different package from the parent class.

So i created a package called p1 and created a class called Car in it :



Now i created another package called p2 and created a class called Alto which extends the Car class :



I am not getting any compilation error , but am getting a runtime exception.Since Alto class inherits the Car class , it should be able to access the protected variable price. Help.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are invoking javac and java from the command line.

If you are compiling the source files by invoking javac from the command line, you might want to use the appropriate destination flag so it places your class file in the correct directory for it be located by the import you have in the other class files you may have.

Once you compile with the destination flag details, you will get the appropriate directories created, i.e p1 and p2. If you do not specify the destination flag, you might get just the .class files in your current directory which is not what you want.

For example if you have a class MyClass.java in package package1, you might want to compile it using javac -d . MyClass.java. This will create a directory called package1 in your current directory and place MyClass.class in it. On the other hand if you compile as follows,

javac MyClass.java

it will simply create MyClass.class in your current directory which is not what you want ( if you want your class file to be located when you import it).

When you're done compiling both your source files you need to invoke java by specifying the appropriate classpath so it can locate the class files.

In your case you might want to do this.

java -cp . p2/Alto

. means current directory. Your import says p1.Car. when you say -cp ., you're specifying where to locate p1.Car.

p2/Alto is the file that you want the jvm to execute. Since your current directory might be different, you need to tell the jvm how to locate Alto.class from your current directory.

Hope that helps.
Chan

 
Abdulla S Mamuwala
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OP, you are right about the protected variable. Can you print your error trace?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!