Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Access a class no package  RSS feed

 
Viet Jav
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2 class A and B

class A:
<no package name>
public class A {
public doIt() {}
}

class B:

package com.abc;
public class B {
// A a = new A();
// a.doIt();
}

In class B, I want to access doIt() method of class A.
So, how do I do?

Help me.
 
Harshil Mehta
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
either include class A into package say com.xyz and import com.xyz.A in class B's source or remove package declaration from class B's source.
 
Viet Jav
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank Harshil Mehta

2 ways you mentioned I can do
But, if do not modify the package name, in class B can I not access method in class A?
 
Eiji Seki
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you can. You can keep your class structure, since that looks like a classpath problem.
Creating classes with no packages is not a good thing, though.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not possible using Sun's recent Java compilers; you might be able to use an older compiler. In that case you'd need to have

import A;

in class B's source file; this syntax is, strictly, not legal Java, but older compilers accepted it. Putting classes in the default package is strongly discouraged, and here's one good reason for that.
 
Viet Jav
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.

I khow creating classes with no packages is not good thing. But class A is not my class(reuse).

I imported A in class B(import A and compile error. And from your message I know it is not possible using Sun's recent Java compilers.
To reuse A, maybe I must remove package name of B class.

Thank you very much.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!