written 8.1 years ago by | • modified 8.1 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 10M
Year: Dec 2015
written 8.1 years ago by | • modified 8.1 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 10M
Year: Dec 2015
written 8.1 years ago by |
Types of Static Members:
Java supports four types of static members
Static Variable:
A class level variable which has static keyword in its creation statement is called static variable.
package com.instanceofjava;
class Demo{
static int a=10;
static int b=20;
}
We can not declare local variables as static it leads to compile time error "illegal start of expression".
Because being static variable it must get memory at the time of class loading, which is not possible to provide memory to local variable at the time of class loading.
package com.instanceofjava;
class Demo{
static int a=10;
static int b=20;
public static void main(String [] args){
//local variables should not be static
static int a=10;// compile time error: illegal start of expression
}
All static variables are executed by JVM in the order of they defined from top to bottom.
And its scope is class scope means it is accessible throughout the class.
package com.instanceofjava;
class StaticDemo{
static int a=10;
static int b=20;
public static void main(String [] args){
System.out.println("a="+a);
System.out.println("a="+b);
show();
}
public static void show(){
System.out.println("a="+a);
System.out.println("a="+b);
}
}
Duplicate Variables:
Even if we change data type or modifier or its assigned value we can not create another variable with same name.
package com.instanceofjava;
class StaticDemo
{
static int a=10;
int a=30;// Compile time error
}
But it is possible to create multiple variables with same name in different scopes.
package com.instanceofjava;
class StaticDemo
{
static int a=10;
int a=30;// Compile time error
public static void main(String [] args){
// it is allowed to define "a" in this method.
int a=20;
}