Statoc and Fianl - 1
Statoc and Fianl - 1
MyMath Example
public class MyMath {
●
In Example 1, to calculate the square of 5
we need to create an instance of MyMath
class:
●
Then we invoke it’s square() method with
the argument 5:
m.square(5);
MyMath Output
●
The results of invoking square() method
on instances m and n are the same:
m: value of PI is 3.14159
m: square of 5 is 25
n: value of PI is 3.14159
n: square of 5 is 25
●
It means that now we have only one
value of variable PI for all instances of
MyMath class; PI is now a class data field
The final keyword
● We declared PI as
public static double PI = 3.14159;
but this does not prevent changing its value:
MyMath.PI = 999999999;
●
This prevents changing the reference
ORIGIN:
MyMath.ORIGIN = new Point(3, 4);
●
Only one instance of a static field data for the
entire class, not one per object.
●
"static" is a historic keyword from C/C++
●
"Class fields" is a better term
– As opposed to "instance fields"
Static Square Method
●
We also added the word "static" to the
declaration of the method square():
●
Static methods do not operate on a specific instance
of their class
●
Have access only to static fields and methods of the
class
– Cannot access non-static ones
●
"Class methods" is a better term
– As opposed to "instance methods"
Java's Math Class
●
Let's take a look at Java's Math class in the API
●
All the methods and fields are static:
Math.sqrt(16)
Math.PI
Math.abs(-3)
Static Field Examples
●
For methods that use only the arguments and therefore do
not operate on an instance
public static double pow(double b, double p)
// Math class, takes b to the p power
●
For methods that only need static data fields
●
Main method in the class that starts the program
– No objects exist yet for it to operate on!
POP QUIZ
●
Speed of light field static
static
● A sum method that returns the resulting of
adding both its arguments
●
Width data field in a Rectangle class non