Nathan Kreider
Nathan Kreider

Reputation: 516

Importing own file into Java class

Okay, not sure if this would work.. but would it be possible, to use my own Java file that has certain required methods in it, to be imported into my Java class just like any other import? Or does it have a special way?

Upvotes: 1

Views: 1355

Answers (4)

Balwinder Pal
Balwinder Pal

Reputation: 97

You Can use Static methods or by create Object of it & Use.

public class abc
{
    public static MyMethod()
    {
        // ..
    }
}

public class pqr
{
    abc.MyMethod();
}

Another Way

public class abc
{

    public void MyMethod()
    {
        // ..
    }
}

public class pqr
{
    abc Obj=new abc();
    Obj.MyMethod();
}

Upvotes: 0

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

If that method is static and visible in your scope, you can use import static. It will make the imported static method look like it is in your class. For example, if your code parse a lot of integers, you can use

import static Integer.parseInt;

And then the parseInt method will be visible and invokable directly:

int parsed = parseInt("123");

Upvotes: 1

Thom Wiggers
Thom Wiggers

Reputation: 7034

That is only required if your other class is in a different namespace. if they are in the same namespace (this includes the default empty namespace), and you 'tell' the compiler about both files, you don't need to use import statements.

If however class A is in namespace org.example.stuffA, and you want to use it in class B in org.example.stuffB, you'll need to use a import org.example.stuffA.A statement, or hard-link it in the document (new org.example.stuffA.A() for example).

In the namespaces example, you still need to make sure the compiler is able to find the required classes. In both cases you also need to make sure the methods you need are of the correct permission type, they would probably need to be public.

Upvotes: 0

Péter Török
Péter Török

Reputation: 116266

If your Java file contains a proper Java class enclosing the methods mentioned above, and it is visible to the compiler (i.e. either its source file is on the compiler source path or its class file is on the compiler classpath), you can just import it like any other classes.

Have you tried it? Do you have any specific problem?

Upvotes: 2

Related Questions