-1

X z = new Y(); means that at compile time it will treat z as an instance of class X, but at runtime as an instance of class Y.

So why is: z.method((byte)0 + (char)0); dealt with at runtime? Aren't these just 2 constants being added up, so it can be determined at compile time, instead of runtime?

class X {
    void method(int x) { System.out.println("X:int"); }
}

class Y extends X {
    void method(int x) { System.out.println("Y:int"); }
}

public class Z {
    public static void main(String[] args) {
        X x = new X();
        X z = new Y();

        System.out.println("1:");
        z.method((byte)0 + (char)0);
    }
}

Output:

1:
Y:int
LifeisHard
  • 125
  • 2
  • 2
  • 10
  • Hint for newbies: you are expected to do prior research. And especially when you are new here/to java: chances are very high that you are not the first person to ask this question. So before spending 15 minutes to write up a good question, spent just a few minutes to check if this question was asked before. – GhostCat Jun 16 '16 at 12:29
  • I know, but how am I supposed to know all the applicable terms? – LifeisHard Jun 16 '16 at 12:30
  • I don't know why the revision history doesn't show it anymore but to others: the original question was about passing `null` to an overloaded method. – Jeroen Vannevel Jun 16 '16 at 12:38

1 Answers1

1

I don't see how the addition is relevant. You have a method add() in X taking an int as parameter. This method is overridden in Y. zreferences an object whose concrete type is Y, so the overriding method in Y is called. That's just plain old polymorphism.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255