how to call methods without instantiation?
In java, is it possible to call methods from an external class without instantiating that class beforehand in the invoker class? If so, how? Thanks!
In java, is it possible to call methods from an external class without instantiating that class beforehand in the invoker class? If so, how? Thanks!
>In java, is it possible to call methods from an external class without instantiating that class
No. You can't only if the method are static
See http://java.sun.com/docs/books/tutorial/reflect/index.html
You can call static methods of a class by using the class name to identify them - ie you do not need to dereference a reference to a particular instance of the class.
what i mean exactly is:
for example:
public class A
{
.....
public int methodA()
.....
}
in another class B, do I have to write:
A instanceA = new A();
int x = A.methodA();
or is there any way i can call methodA straight away without instantiate "instanceA"?
this only can be done if the class b extends the class a, then you can use syntax below,
super.mathod();
sorry... typing error... should be "instanceA.methodA()"...
but no other ways? i mean call method directly...
As has been said already you can call static methods without an instance.
class A {
public static void method() {...}
}
//Somewhere else
A.method();
I think there is only above mentioned ways to call a method directly. In java every function and variable is written in a class. So
> sorry... typing error... should be
> "instanceA.methodA()"...
>
> but no other ways? i mean call method directly...
If you wish to access the function even without mentioning the class name, it is not possible.
> As has been said already you can call static
> methods without an instance.
> class A {
>public static void method() {...}
>
> //Somewhere else
> A.method();
And with static imports you can do:
//Somewhere else
import static A.method;
//...
method();
-Puce
> sorry... typing error... should be
> "instanceA.methodA()"...
>
> but no other ways? i mean call method directly...
Let's try a different approach. Why do you think you need to do this? Your questions should be about your actual problem, not what you reckon will be the solution to your problem - you'll get a decent answer much quicker!