Wondering about the output of the following Java program

98 Views Asked by At

I am dealing with some past exam papers and here I am not sure of the output. I think I am not clear about extends and super.

public class Superclass{
    public boolean aVariable;

    public void aMethod(){
        aVariable = true;
    }
}

class Subclass extends Superclass {
    public boolean aVariable;

    public void aMethod() {
      aVariable = false;
      super.aMethod();
      System.out.println(aVariable);
      System.out.println(super.aVariable);
    }
}

I think that the second output would be true since it would refer to the super class and it is an object. However, I am not sure of the first output. Would it be just a value and print false or it is also an object?

4

There are 4 best solutions below

7
On BEST ANSWER

The output will be:

false
true

Because in your Subclass aVariable is false by default (so assignation aVariable = false; is needless). Read more about Primitive Data Types default values.
And in Superclass you initialize aVariable as true by invoking the superclass' method using the keyword super: super.aMethod();. Read more about Accessing Superclass Members.

Take a look on demo.

0
On

I conducted scientific experiment (copy-pasted and ran) and it prints false true

More here:

If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

0
On

Since they're both scoped to their own class block, having them with the same name doesn't matter. As it looks like now, you set aVariable to false, the call to the super doesn't change that, except for creating another variable (new reference) with the same name and sets it to true. So the expected output would be

false
true
2
On

Output will be:

false
true

super.aMethod() will execute making aVariable = true of SuperClass

aVariable of SubClass will remain false.