OOP - Java Static Members Examples
OOP - Java Static Members Examples
OOP - Java Static Members Examples
Example 1: Modify static variable in main method and other methods of the class
class Main
{
// static variables a and b
static int a = 10;
static int b;
Counter()
{
count++;//incrementing the value of static variable
System.out.println(count);
}
}
class Main
{
public static void main(String args[])
{
System.out.println("Values of static counter:");
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Example 3: Static Method
class Main
{
// static method
static void static_method()
{
System.out.println("Static method in Java...called without any
object");
}
classBase_Class {
obj1.static_display();
obj2.static_display();
obj3.static_display();
}
}
class Main
{
static int sum = 0;
static int val1 = 5;
static int val2;
// static block
static {
sum = val1 + val2;
System.out.println("In static block, val1: " + val1 + " val2: "+ val2 + " sum:" +
val2 = val1 * 3;
sum = val1 + val2;
}
Example: Multiple Static Blocks in Java (in sequence execution, valies of first block are overwritten by second block
class JavaExample2{
static int num;
static String mystr;
//First Static block
static{
System.out.println("Static Block 1");
num = 68;
mystr = "Block1";
}
//Second static block
static{
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
class JavaExample{
static int i = 100;
static String s = "Beginnersbook";
//Static method
static void display()
{
System.out.println("i:"+i);
System.out.println("i:"+s);
}
//non-static method
void funcn()
{
//Static method called in non-static method
display();
}
//static method
public static void main(String args[])
{
JavaExample obj = new JavaExample();
//You need to have object to call this non-static method
obj.funcn();
class Human{
....
}
class Boy extends Human{
public static void main( String args[]) {
/*This statement simply creates an object of class
*Boy and assigns a reference of Boy to it*/
Boy obj1 = new Boy();
Counter(){
count++;//incrementing value
System.out.println(count);
}
// non-static method
int multiply(int a, int b){
return a * b;
}
// static method
static int add(int a, int b){
return a + b;
}
}