Created
September 3, 2017 17:24
-
-
Save LazaroIbanez/2f2cdc8f1765bd4a7774e7a536f90850 to your computer and use it in GitHub Desktop.
Behaviour of the static and instance variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class B { | |
public static void main(String… args) { | |
System.out.println(“Value of var1 = “+B1.var1); | |
System.out.println(“Object 1”); | |
B1 object1 = new B1(); | |
object1.printData(); | |
System.out.println(“Object 2”); | |
B1 object2 = new B1(); | |
object2.printData(); | |
object2.increment(); | |
object2.printData(); | |
B1.staticIncrement(); | |
object2.printData(); | |
} | |
} | |
class B1 { | |
static int var1; //var1 = 0 only when class is loaded not for each object created | |
int var2; //instance variable var2 = 0 | |
B1() { //Constructor incrementing static variable var1 | |
var1++; | |
} | |
public void printData() { | |
System.out.println(“Value of var1 = “+var1); | |
System.out.println(“Value of var2 = “+var2); | |
} | |
public void increment() { | |
var1++; | |
var2++; | |
} | |
public static void staticIncrement() { | |
var1++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment