String addition
In this code though there is no mention in the code to explicitly print "20
"
Actually there is, take a look at your Superclass
Superclass() {
this(0);
System.out.println("1");
}
Superclass(int x) {
System.out.println("2" + x);
}
Addition of String
s is interpreted as concatenation, not as ordinary addition (of values). So calling the default constructor of Superclass
triggers this(0)
which yields
System.out.println("2" + x);
=> System.out.println("2" + 0);
=> System.out.println("20");
thus printing 20
.
Integer addition
If you want to add the values as integer you need to use int
values and not String
values, for example like
Superclass(int x) {
System.out.println(2 + x);
}
then you will also get
System.out.println(2 + x);
=> System.out.println(2 + 0);
=> System.out.println(2);
Constructor-chain
Okay, so what happens exactly if you call
Subclass s = new Subclass(10, 20);
Well, first, of course, you trigger this constructor
Subclass(int x, int y) {
System.out.println("4" + x + y);
}
Now in Java, when creating sub-classes you will always need to call one of the constructors of the super-class (it's per definition of the language).
And if you don't explicitly specify such a call then it tries to call the default constructor of your super-class. If there is no, it won't compile. However you have such a default constructor, the code will thus be equivalent to
Subclass(int x, int y) {
// Implicit call of default super-constructor
super();
System.out.println("4" + x + y);
}
So you call the following constructor
Superclass() {
this(0);
System.out.println("1");
}
which, as shown above, triggers the other constructor
Superclass(int x) {
System.out.println("2" + x);
}
So what you will get, if resolving this chain, are the following outputs
// from Superclass(int x)
System.out.println("2" + 0);
// from Superclass()
System.out.println("1");
// from Subclass(int x, int y)
System.out.println("4" + 10 + 20);
which yields
20
1
41020