Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method without object

Tags:

java

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?

like image 606
Nathan Kreider Avatar asked May 31 '12 06:05

Nathan Kreider


People also ask

How do you call a method without an instance?

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.

Can we call a method without creating an object Python?

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.

Can we call method with null object?

But just to make it clear - no, you can't call an instance method with a null pointer.

Which keyword helps to access a method without an object?

The keyword static is used to denote a field or a method as belonging to the class itself and not to any particular instance.


2 Answers

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();
}
like image 180
npinti Avatar answered Sep 22 '22 11:09

npinti


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.

like image 44
tagtraeumer Avatar answered Sep 22 '22 11:09

tagtraeumer