• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding Package and Import  RSS feed

 
jnrohit Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have following piece of code:

ClassA in C:\java

ClassB in C:\java

How to import ClassA in ClassB so ClassB compile and execute successfully? Do I need to use classpath to compile and execute ClassB code?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jnrohit Jain wrote:
How to import ClassA in ClassB so ClassB compile and execute successfully? Do I need to use classpath to compile and execute ClassB code?


Simply. You can't. It is a compile error to import a class from the default package. Only classes in the default package can use classes in the default package. It used to be allowed, but not anymore -- not sure when the rule (specification) was changed though.

Sorry,
Henry
 
Dave Tolls
Ranch Foreman
Posts: 3065
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since ClassB is declared as being in a package com.pkg1 then, since you say it is in C:\java, it is in the wrong directory.
It should be in (assuming C:\java is the root for your source files) in C:\java\com\pkg1.

That's the first thing.
The second is that ClassA should also be in a package.
You'll have issues importing if it isn't.  You can't import from the default (unnamed) package.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remind yourself about packages in the Java™ Tutorials. Also note the section about package names; the package name com.pkg1 shou‍ld belong to whoever owns pkg1.com.
 
Dave Tolls
Ranch Foreman
Posts: 3065
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:... the package name com.pkg1 shou‍ld belong to whoever owns pkg1.com.


Someone through GoDaddy, by the look of it.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but fortunately they didn't seem annoyed, so they probably haven't noticed the package name. Pheww!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!