0

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);

    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Lsc1408
  • 1
  • 1
  • 1
    The example makes no sense whatsoever. What exactly are you trying to achieve and more importantly, what book are you trying to learn Java from?! – justanotherguy May 19 '22 at 05:26

3 Answers3

0

This is what happens:

  1. new Minor() constructs an object of the Minor class and calls the ctor of the Uber class in the super(y) statement.
  2. this() increments y by 1, so y becomes 3 (take a look at the default ctor)
  3. then the next line overwrites it to 3*2 which is 6
  4. finally y += 3 makes y 6

Please tell me if you need any more clarification

justanotherguy
  • 399
  • 5
  • 16
0

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
Max Peng
  • 2,879
  • 1
  • 26
  • 43
  • This seems to explain the result of code, but doesn't answer the question asked _"Is new Minor(); in main function creating an object or is it something related to constructor?"_ – Mark Rotteveel May 20 '22 at 13:14
-1

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.

ndc85430
  • 1,395
  • 3
  • 11
  • 17