i must have spent on hour trying figure out reason unexpected behavior. ended realizing field wasn't being set i'd expect. before shrugging , moving on, i'd understand why works this.
in running example below, i'd expect output true, it's false. other tests show whatever type default value is.
public class classone { public classone(){ firemethod(); } protected void firemethod(){ } } public class classtwo extends classone { boolean bool = true; public classtwo() { super(); } @override protected void firemethod(){ system.out.println("bool="+bool); } public static void main(string[] args) { new classtwo(); } } output:
bool=false
boolean bool = true; public classtwo() { super(); } is identical to
boolean bool; public classtwo() { super(); bool = true; } the compiler automatically moves fields initializations within constructor (just after super constructor call, implicitly or explicitly).
since boolean field default value false, when super() called (and classone() , firemethod()), bool hasn't been set true yet.
fun fact: following constructor
public classtwo() { super(); firemethod(); } will understood as
public classtwo() { super(); bool = true; firemethod(); } by jvm, , output be
bool=false bool=true
Comments
Post a Comment