java-static
Static field: Field is shared in all the object of the class
Inner Class Could not have static field
In Java8, Static field has to be declared in Interface
Exercice :
Q1)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27package com.cyrgue.staticKeyword;
class X {
static int MAX_VAL = 100;
int value = 99;
public void setValue(int x) {
if (x <= MAX_VAL) {
value = x;
}
}
}
public class StaticPrg {
public static void main(String[] args) {
X a = new X();
X b = new X();
a.setValue(120);
System.out.print(a.value + ",");
b.MAX_VAL = 150; // better is X.MAX_VAL = 150
a.setValue(140);
System.out.println(a.value);;
}
}
What happens?
A) I’m an X
B)
C) 99, 140
D)
Response : C
X does not have a method doStuff2()
Static Methods and heritance
1 | package com.cyrgue.staticKeyword; |
What is the result?
A) Y-Hello, Y-Hello2
B) Y-Hello, Z-Hello2
C) Z-Hello, Z-Hello2
D) Y-Hello, Y-Hello2
E) Compilation Fails
Response :
B :
Y y = new Z();
y.sayHi2() is an INSTANCE METHOD
so means send a message from the OBJECT (instance)(of type Z) - NOT the type of the POINTER
static method is treated differently
the compiler replaces the y.sayHi() with Y.sayHi() as it’s static so this is the POINTER TYPE
If you invoke static method, the behavior is determined statically by the compiler, so it uses the type of the variable (the POINTER) so Y
For instance method, dynamic method invocation(object (not pointer)of y, send a message),
Type of referee (Z) must be “assignment compatible” with type of reference (Y)