I have built a small (and 3 methods only!) api for myself, and I want to be able to call it like how you would call a method in Powerbot (A Runescape botting tool (I use it, but for programming purposes, not for actual cheating purposes)), without creating an Object of the file you'd require. How would i be able to do this?
If the method is "class method" i.e static, you can use the class name directly to invoke such method, you dont need an object of the class, but its still valid to call static methods on an object but then the compiler will substitute the class name.
Static method can be called without creating an object or instance. Simply create the method and call it directly. This is in a sense orthogonal to object orientated programming: we call a method without creating objects.
But just to make it clear - no, you can't call an instance method with a null pointer.
The keyword static is used to denote a field or a method as belonging to the class itself and not to any particular instance.
You will need to create static methods, so you will need to do something like so:
public class A
{
public static void foo()
{
...
}
}
And then, you can call them like so:
public class B
{
...
A.foo();
}
Note however that static
methods need to be self contained.
EDIT: As recommended in one of the answers below, you can make it work like so:
package samples.examples
public class Test
{
public static void A()
{
...
}
}
And then do this:
import static sample.examples.Test.A;
public class Test2
{
...
A();
}
If you use the static keyword when importing your class, you can use its methods as if they belong to the class you're importing them to. See:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
And of course your "api methods" need to be static as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With