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 |
package com.cyrgue.staticKeyword; |
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)
近期评论