0

When I try running this piece of code, it gives me 30. Can someone please explain!I know you can't override static methods in Java, because, polymorphism and static won't work together. And static methods are invoked on Class, not in instances. but can someone please explain further on this topic. I don't really understand why i am getting a 30 and not 10. thanks!

class One {

    static int value = 0;
    One(){
        addValue ();
    }

    static int addValue () {
        return value+=10;
}

    int getValue () {
        return value;

     }

}

class Two extends One {

    Two () {
        addValue ();
    }

    static int addValue () {
        return value+=20;
    }

public static void main(String[] args ) {
    One t = new Two ();
    System.out.println(t.getValue());
}
}
loreen99
  • 43
  • 7

4 Answers4

5

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. Reference : Oracle doc

If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

Here in your case, you are calling constructor of class Two which invokes constructor of class One by default which has method call addValue defined which adds 10 to value.

So now value = 10. After that, addValue method of class Two invoked which adds 20 to value. so finally you are getting value = 20 + 10 = 30 as output.

Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
3

When you try to run this program initially as you are creating an instance of class Two, inside its constructor there is a statement 'super()' which calls super class constructor automatically by the compiler. So, first the value of variable 'value' is 10 and then it is incremented by 20. Finally its value is 30 which you are getting as a result.

Here's the code treated by compiler:

Two () {
    super();   // Automatically invoked by compiler
    addValue ();
}
Viswanath Donthi
  • 1,791
  • 1
  • 11
  • 12
0

You are calling the constructor of Two class. But when you calling that implicitly your One class constructor will be called . so it will add 10 to your value variable after that it will call the Two Constructor and `addValue method in that class. So it will add another 20 to your value variable . So answer will be 30.

MeshBoy
  • 662
  • 5
  • 9
0

The Two class constructor first calls the super class (One) constructor.

One calls addValue() in its' own class. This adds 10 to the value (0 + 10 = 10).

Then when One's constructor finishes, Two's constructor begins. Two then calls addValue() itself. This adds another 20, bringing the value field (shared by One and Two, due to inheritance) to a total of 30.

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28