This class has methods that do mathematical calculations...I know...duh. Well, the methods of the Math class are static, meaning you don't have to instantiate an object to call them. You can simply call them like this.
Math.METHOD(parameters_used);
You DON'T have to do this:
Math mathObject = new Math(); mathObject.METHOD();
You don't HAVE to do it that way...but you can, but no one I know does that.
Well, we'll make a method that does a very simple calculation. We'll make an addition() method.
class OurMath
{
public static int addition(int a, int B)/>
{
int sum = a + b;
return sum;
}
}
Notice how we declare our int return type for the method. This makes it so we can assign it to an int variable in a main method or something.
Also notice the int variables in the parentheses. These are called 'parameters'. These are what's going to be included in the method when it's called.
It's going to be called like this.
int number = OurMath.addition(1, 3);
Well, anyone know what number is going to equal after that? That's right! Four!
You HAVE to call the method with 2 parameters. If you call it any other way, you're going to going to get a compile error saying something along these lines. cannot find symbol: method addition(int)
static Class Variables
Well, back again to the Math class. It has 2 double variables, E, and PI.
class Math
{
static double E = 2.718...;
static double PI = 3.141596535...;
}
This is how we declare static (AKA "class") variables. Let's go back to our class...
class OurMath
{
static int five = 5;
public static int addition(int a, int B)/>
{
int sum = a + b;
return sum;
}
}
Well, now we can access our five variable through doing this.
int ourVariable = OurMath.five;
The main reason of using static is to make non "object"-ive data or methods.
Hope this tutorial helped anyone that needed it!







MultiQuote






|