'Can you explain what is new Minor(); in this code? [duplicate]
Is new Minor(); in main function creating an object or is it something related to constructor? (I am new to Java so I didn't understand this example)
class Uber {
static int y = 2;
Uber(int x) {
this();
y = y * 2;
}
Uber() {
y++;
}
}
class Minor extends Uber {
Minor() {
super(y);
y = y + 3;
}
public static void main(String[] args) {
new Minor();
System.out.println(y);
}
}
Solution 1:[1]
Actually, if you understand the java constructor execution order well, it is very easy to tell the output is 9.
You add more print to understand the execution order like this:
class Uber {
static int y = 2;
Uber(int x) {
this();
y = y * 2;
System.out.println("after uber#this: "+ y);
}
Uber() {
y++;
System.out.println("after uber#default: "+ y);
}
}
class Minor extends Uber {
Minor() {
super(y);
y = y + 3;
System.out.println("after super: "+ y);
}
public static void main(String[] args) {
System.out.println("main: "+ y);
new Minor();
System.out.println(y);
}
}
Which will print like this:
main: 2
after uber#default: 3
after uber#this: 6
after super: 9
9
Solution 2:[2]
This is what happens:
new Minor()constructs an object of the Minor class and calls the ctor of the Uber class in thesuper(y)statement.this()incrementsyby 1, so y becomes 3 (take a look at the default ctor)- then the next line overwrites it to 3*2 which is 6
- finally
y += 3makesy6
Please tell me if you need any more clarification
Solution 3:[3]
new Minor() just creates a new instance of the Minor class, by calling its default (i.e. no-argument) constructor. That instance is just thrown away, since there's no assignment statement. It doesn't seem to be useful code at all, though.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Max Peng |
| Solution 2 | |
| Solution 3 | ndc85430 |
