简体   繁体   中英

Java Inheritance. Interesting thing

Consider having the piece of code:

public class Base {
    int a = 1;

    public int getA() {
        System.out.print("Super");
        return a;
    }

    public static void main(String[] argv) {
        Base base = new Sub();
        System.out.println(base.a + " " + base.getA());
        System.out.println(base.getA());
        System.out.println(base.a);
    }
}

class Sub extends Base {
    int a = 2;

    public int getA() {
        System.out.print("Sub");
        return a;
    }

}

And the output is:

Sub1 2
Sub2
1

Can somebody explain me the output? Why System.out.println(base.a + " " + base.getA()); and System.out.println(base.getA());System.out.println(base.a); give different output?

I consider that the output to System.out.println(base.a + " " + base.getA()); should be Sub2 1

Do you have any ideas?

This code

System.out.println(base.a + " " + base.getA());

prints

Sub1 2

because getA() (and its System.out.println("Sup")) is called before the String is created and println finishes executing.

The steps are like this

  1. System.out.println(base.a + " " + base.getA()); is called
  2. base.getA() is called, executing System.out.print("Sub"); and returning 2 . At this point, Sub is printed to out .
  3. A String is created as the concatenation of base.a , which is the value 1 and the return of 2 , which is the value 2
  4. The resulting String of 3 is printed, the String 1 2
  5. The output already contains Sub , then the result of 4 gets appended to that, so Sub1 2 .

Why System.out.println(base.a + " " + base.getA()); and System.out.println(base.getA());System.out.println(base.a); give different output?

In the first case you're printing base.a first and base.getA() second. In the second case you're printing base.getA() first and base.a second. So obviously the numbers will be the other way around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM