6

How do you call a method from a different class (file) in java?

Are objects required? Or is there a 3rd way to make a merge of documents for java? Can we use a simple method call of is there a proper way to call new methods?

4
  • 6
    This is a very general question, I think you need to go and read on some Java basics... Commented Apr 11, 2017 at 15:41
  • 1
    Are objects required? - in Java every method is at least located in a class. To call static methods you need the class, to call instance methods you need an instance of that class. Commented Apr 11, 2017 at 15:42
  • "make a merge of documents" - What do you mean by "document"? Commented Apr 11, 2017 at 15:44
  • Java files don't exist in the running program. The files exist only to convey code to the JVM. Once in there, there's no "file" making calls, only methods. How method​ calls work is well explained in the Java Tutorial, which I strongly advise you to read. Commented Apr 11, 2017 at 16:21

2 Answers 2

20

Your question is not clear to me, as far as I understand you want to call a method of another Java file (I assume another Java class).

So consider you have java files A.java and B.java. So you have definitely two classes A and B.

Now if you want to call a method of B class from A class you need to:

  1. Make the method of B class public (or public static)
  2. Create a object of B class in A (or if method is static this step is not required)
  3. Using that object(in case of static user class name) call the method

Take a look:

• Non-static method:

B.java

class B {
   public void myMethod() {
     // do stuff
   }
}

A.java

class A {
    public void anotherMethod()
    {
         B b=new B();
         b.myMethod();        // calling B class's method
    }
}

• STATIC method:

B.java

class B {
   public static void myMethod() {
     // do stuff
   }
}

A.java

class A {
    public void anotherMethod()
    {
         B.myMethod();        // calling B class's method
    }
}
Sign up to request clarification or add additional context in comments.

aMethod() is more like a constructor there, not a method ;-)
Ooooops... updated :p
myMethod is a better name to call the method in order not to be confused with A, I think
agreed @DirtyDev :D
1

you can try packaging your class

using package com.yourwebsite; at the very start of your class and above import statements

then at the cmd type javac -d . YourClass.java

then you can import it on the next class that you are trying to create

to import it use import com.yourwebsite.YourClass;

note that your package doesn't allow wild card symbol so you must use the full name of your class

I don't think this is what he asked for...
Yes @Celt, but this basic steps can be useful for very begginers in Java programming.
Yes, but unrelated to the question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.