Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one java file call methods from another java file? [closed]

Tags:

java

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?

like image 461
Brian Quinones Avatar asked Aug 25 '26 01:08

Brian Quinones


1 Answers

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
    }
}
like image 51
KOUSIK MANDAL Avatar answered Aug 27 '26 14:08

KOUSIK MANDAL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!