+ 1

which one is called? what is the output? why? what is the difference? (Q2 is more important for me)

imagine these classes: class Parent{ public void f(){ System.out.println("f() in Parent"); } } //-------------------------------------------------------------- class Child extends Parent{ public void f(){ System.out.println("f() in Child"); } } //-------------------------------------------------------------- public class SomeClass { public void method(Parent p){ System.out.println("method(Parent)"); } public void method(Child p){ System.out.println("method(Child)"); } } //-------------------------------------------------------------- Now I have 2 Questions: Q1: Parent obj1 = new Child(); obj1.f(); Q2: SomeClass obj2 = new SomeClass(); Parent obj3 = new Child(); obj2.method(obj3);

14th Feb 2017, 11:40 AM
Mohammad Reza Moosaei
Mohammad Reza Moosaei - avatar
1 Answer
+ 1
q1: f() in Child() q2:metod(Parent). java checks types at compile time. obj3 defined as Parent. that is why compiler chooses method(Parent p). the difference is that in q1 type is checked at runtime.
14th Feb 2017, 8:14 PM
Ivan Terenkovskiy
Ivan Terenkovskiy - avatar