Reputation: 3548
I am a newbie in java and googling did not help me. So, bear with me...:P
I created a package acs
. This package has got the class Gets
which has the method foo()
.
Now, I created another class in the same package and tried to call the method foo()
. Of course this will work - (new Gets()).foo();
.
But I added an import import acs.Gets;
and simply tried to use the method directly - foo();
as described in http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html. But unfortunately, the code did not work. Please tell me where am I going wrong. Any help will be appreciated!
Upvotes: 4
Views: 6214
Reputation: 1
THERE ARE 3 WAYS TO RESOLVE THIS.
Var random = new Gets(); //or Gets random = new Gets(); /*these both have the same effect.*/
//Then use the method like this:
random.foo() //or System.out.print(random.foo());
/*
depending on whether your method returns a Primitive Type or Void, and its function.
*/
Gets.foo(); //simple as that
public class acs extends Gets{
public static void main(String[] args){
/* method called without Objects or Class references. */
foo();
} // ends Main()
}// ends acs() Class
Upvotes: 0
Reputation: 6188
You can only import a function from another class if that function is static; so for example this will work:
public class Gets {
public static void foo() {}
}
and then import it:
import static acs.Gets.foo;
If it isn't static however you won't be able to import it.
EDIT: As was pointed out in the comments, using static imports can make code more difficult to read, so they should be used with caution. They can be useful if used correctly though.
Upvotes: 13
Reputation: 10086
You would still need to create an object to access the non-static method:
(new Gets()).foo();
And you will still need to declare the class to access a static method:
Gets.staticFoo();
You don't need to import a class from the same package. It is superfluous as all classes in a package are already visible to each other.
Also, you are also confusing yourself about how imports work. Importing a class does not mean that its method or fields become accessible without qualification.
The reason why one imports a class from another package, is so that one does not have to declare the package everywhere in code. Instead of writing:
acs.anotherpkg.Blah testblah = new acs.anotherpkg.Blah();
You can simply write:
import acs.anotherpkg.Blah;
...
Blah testblah = new Blah();
Upvotes: 0
Reputation: 2053
Java is Object oriented. You need to create an object of the class for you to invoke methods of the class.
So something like
new Gets().myFunction();
is bound to work.
The only exception to this rule is to create a static
method. You can find out when to create static methods and if they suit your requirement, but to access a method of a class, you need an object.
Upvotes: 0
Reputation: 4923
You can't access the method of another class without its object whether both the class exist in same package or not.
Upvotes: 0