简体   繁体   中英

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?

If your Java file contains a proper Java class enclosing the methods mentioned above, and it is visible to the compiler (ie 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?

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");

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 .

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM