Static Members
https://www.computersprofessor.com/2016/06/static-members.html
A
class basically contains
two sections, one declares variables
and the other
declares methods. These variables
and methods are called
instance variables and
instance methods. This is
because every time
the class is
instantiated a new copy
of each of them are
created they are
accessed using the
objects with( ) operator .
if we want to
define a member i.e
in common to
all the objects
and accessed with out
using a particular object
.i.e the member belongs
to the class as
static
int x;
static
int largest (int x,
int y);
The members
that area declared static are called
static members. Since these
members are associated with
the class itself rater
then individual objects, the
static variables and static
members are often
refer to as
class variables and
class methods. Static variables
are used when
we wait to have a
variable common to all
instances of a class. Like static
variables, static methods can be
called with out using the
objects. They are also available
for use by
other classes.
Methods that
are of general but
do not directly effect
as instance of
that class are usually declared as
class methods.
For eg math class of
java library defines many
static methods to
perform math opetions
float
x=Math.sqrt (25.0);
The method sqrt ( ) r a
class method (or
static method) defined in
math class. We can
define ar oun static methods as
shown in the following example.
class MathOperations
{
static float
mul(float x , float y)
{
return
x * y;
}
static float div ( floatx, float y)
{
return x/y;
}
}
class MathMain
{
public static void main (string
args[])
{
float a=MathOperation.mul(4.0,5.0);
System.out.println(“a=”+a);
float b= MathOperation.div (9,2.0);
System.out.println(“b=” +b);
}
}
Note that the
static methods are called
using class names. No objects have
been created for use static methods. static methods have
several restrictions.
1)
They
are only call other static
methods.
2)
They can
only access static
data.
3)
They can’t
refer to this
or super in
any way.