I'm looking at the code below and found something a bit strange:
public class Sequence {
Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
I would've expected this to give a compilation error as the System.out
with "y " doesn't belong to a method declaration just a { }
. Why is this valid? I don't see how this code would or should be called.
When running this it produces x y c g
also, why does the static { }
get called before the sequence constructor?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…