开发者

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) {
  retu开发者_如何学Crn one + two;
}

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


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.


You can create a Utility class like

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


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)


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜