JAVA STATIC KEYWORD
JAVA STATIC KEYWORD
If the value of the variable is not varied from objects to objects then it is not recommended to declare variable as instance variable. We have to declare such type of variable at class level by using static modifier.
In instance variable for every object a seprate copy will be created but in case of static variable a single copy will be created at class level and it is share by every object of the class
static keyword can be used it
1. variable
2.method
3.block
4.nested class
program to explain static keyword and its use
class Dog //can be either default or public cant be static
{
int x;//instance member variable
public static int y;//static member variable
public void fun1()//instance member function
{
System.out.println("hello i am in instance member function");
}
public static void fun2()//static member function
{
System.out.println("hello i am in static memeber function");
}
static class SQL
// static inner class it can be public, private, protected,default,synchronized
{
static String country="INDIA";
}
}
public class Test// main class
{
public static void main (String args[])
{
Dog d= new Dog();
System.out.println("hello we are in instance member variable"+(d.x=12));
// calling instance member variable
System.out.println("hello we are in static member variable"+(Dog.y=12));
// calling static member variable
d.fun1();// calling instance member function
Dog.fun2();//calling staic member function
System.out.println(Dog.SQL.country);//calling static inner class
}
}
Comments
Post a Comment