LA_
LA_

Reputation: 20409

How to use the same function in several java classes?

I can not understand how to use the same function in several java classes. For example, I have the following function:

public int plus(int one, int two) {
  return one + two;
}

How can I use that in several other files (classes)? Should I create that in separate class?

Upvotes: 1

Views: 195

Answers (6)

Peter Lawrey
Peter Lawrey

Reputation: 533432

You can create a Utility class like

public enum Maths {;
    public static int plus(int one, int two) {
        return one + two;
    }
}

Upvotes: 3

Eng.Fouad
Eng.Fouad

Reputation: 117569

Or you can do it like this:

class Test
{
    public int plus(int one, int two)
    {
        return one + two;
    }
} 

Then use it like:

int i = new Test().plus(1,2);

Upvotes: 0

Eternal_Light
Eternal_Light

Reputation: 686

This function you created has to be inside a class. If you go and create an instance of this class in another class of yours (in the same package) ex: Let's say you have this

public class Blah {
  public int plus (int one, int two) {
    return one + two;
  }
}

and then you have the class where you want to use blah:

public class otherclass {
  public void otherfunc{
    int yo,ye,yu;
    Blah instanceOfBlah = new Blah ();
    yu = instanceOfBlah.plus(yo,ye);
  }
}

You can use this way in any of your other classes to access the plus function. If those other classes belong to different packages you might have to import the blah class tho.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

You should create a class and add that function to it. Then call that function in another class such as the Test class which contains a main method.

public class Util{
   public static int plus(int one, int two) {
     return one + two;
   }
}

class Test {
    public static void main(String args[])
    {
       System.out.println(Util.plus(4,2));
    }
}  

Upvotes: 0

tog000
tog000

Reputation: 151

If the implementation is always going to be the same (one+two), you could instead turn it into a static method, like this:

class Util{
    public static int plus(int one, int two) {
        return one + two;
    }
}

Then you can call the function like

int result = Util.plus(1,1)

Upvotes: 2

Howard
Howard

Reputation: 39177

If you put the function into a class and declare it static

class MathFunctions {
  public static int plus(int one, int two) {
    return one + two;
  }
}

you can always access it like this:

Mathfunctions.plus(1, 2);

If you have a non-static method you must always call it with reference to an actual object of the class you have declared the method in.

Upvotes: 5

Related Questions