Class Methods and Class Variables
Previous | Home | Next |
Class method:-Methods declared with "static " keywords is called class methods.
Class variable:- Variable declared with "static" keyword is called class variable.
Class variable:-
When a variable is declared with the static keyword, its called a “class variable”.
All instances share the same copy of the variable.
A class variable can be accessed directly with the class, without the need to create a instance.
Class methods:-
Methods can also be declared with the static keyword.
When a method is declared static, it can be called/used without having to create a object first.
method declared with static can access the variable with static keyword only
Syntax Class Variable
static int y=0; // class variable
Syntax Class Method
static int triple (int a)
Class variableclass Demo2
{
int x = 0; // instance variable
static int y=0; // class variable
void setX (int n) // method declare
{
x = n;
}
void setY (int n)
{
y = n;
}
int getX () //method declare
{
return x;
}
int getY ()
{
return y;
}
class Demo1 //subclass
{
public static void main(String[] arg)
{
Demo2 x1 = new Demo2(); //instance/object of super class
Demo2 x2 = new Demo2(); //instance/object of super class
x1.setX(10); // calls the set method of super class with the
//objects x1 n x2 both have different values
x2.setX(15);
// each x1 and x2 has separate copies of x
System.out.println( x1.getX() );
System.out.println( x2.getX() );
// class variable can be used directly without a instance of it.
//(if changed to t2.x, it won't compile)
System.out.println( Demo2.y );
Demo2.y = 7;
System.out.println( t2.y );
Class method
// A class with a static method
class 2
{
static int triple (int a)
{
return 3*a;
}
}
class Demo1 {
public static void main(String[] arg)
{
// calling static methods without creating a instance
System.out.println( Demo2.triple(4) );
// calling static methods thru a instance is also allowed
Demo2 x1 = new Demo2();
System.out.println( x1.triple(5) );
}
}
Previous | Home | Next |