• Post Reply Bookmark Topic Watch Topic
  • New Topic

Strange behaviour of inherited classes

 
Chandra Bairi
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the following code. the output for this code is given against the println statements.
class Base {
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base {
public boolean foo(Sub s) {
return false;
}
}
public class Test {
public static void main(String argv[]) {
Base bb = new Base();
Base bs = new Sub();
Sub ss = new Sub();
System.out.println(bb.foo(bb)); //true
System.out.println(bs.foo(bs)); //true
System.out.println(bs.foo(ss)); //true
System.out.println(bs.foo(bb)); //true
System.out.println(ss.foo(bs)); //true
System.out.println(ss.foo(bb)); //true
System.out.println(ss.foo(ss)); //false
}
}

Also see this code:

class Base {
public boolean foo(int b) {
return true;
}
}
class Sub extends Base {
public boolean foo(int s) {
return false;
}
}
class Test2 {
public static void main(String argv[]) {
Base bb = new Base();
Base bs = new Sub();
Sub ss = new Sub();
System.out.println(bb.foo(10)); //true
System.out.println(bs.foo(10)); //false
System.out.println(bs.foo(10)); //false
System.out.println(bs.foo(10)); //false
System.out.println(ss.foo(10)); //false
System.out.println(ss.foo(10)); //false
System.out.println(ss.foo(10)); //false
}
}
What is interesting is that in the source code given above the values are true(6 times) followed by false and in the code below the o/p is true followed by false(6 times). In the above code how is the resolution done.I have read in many books that the runtime resolution for methods is done based on the object and not on the reference. in that case the first code should give the same o/p as the second one and we can also see that the subclass in first code can be assigned to super class also so it is perfect for the o/p to be as the 2nd one.
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to the Beginners forum
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!