Results 1 to 5 of 5
Thread: Doubt in run time polymorphism
- 07-20-2009, 09:30 AM #1
Doubt in run time polymorphism
Could You explain the program flow and output?
Java Code:package com; class Alpha { public void foo(String... args) { System.out.println("Alpha:foo"); } public void bar(String a) { System.out.println("Alpha:bar"); } } public class RegExCheck extends Alpha { public void foo(String a) { System.out.println("Beta:foo"); } public void bar(String a) { System.out.println("Beta:bar"); } public static void main(String[] args) { Alpha a = new RegExCheck(); RegExCheck b = (RegExCheck) a; a.foo("test"); b.foo("test"); a.bar("test"); b.bar("test"); } }One Life!!! Y Serious??? :)
- 07-20-2009, 03:11 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
- 07-20-2009, 03:16 PM #3
1) I get O/P as Alpha:foo Beta:foo Alpha:bar Beta:bar
2) I expected it to be Beta:foo Beta:foo Alpha:bar Beta:bar
2) I expected (2) because object a is created of the reference type Beta and hence at run time it should call method Beta class.One Life!!! Y Serious??? :)
- 07-20-2009, 03:52 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
You do? That's not either what I expect, or what I get. Did you write the code correctly, or was bar() supposed to be static?
Well, as you suspect, that's not correct either.
The runtime looks for the foo() function that matches a.foo(), which takes a String. It finds one called foo(String...). It then looks to see if it's overridden by the subclass, and doesn't find a child version of foo(String...), so it sticks with the Alpha method it has found.
At least, that's the gist of its decision making.
- 07-21-2009, 08:17 AM #5
Similar Threads
-
is Polymorphism the tool to use?
By xcallmejudasx in forum New To JavaReplies: 2Last Post: 05-04-2009, 05:02 PM -
Polymorphism Help
By AWPtic in forum New To JavaReplies: 5Last Post: 04-06-2009, 04:13 PM -
inheritance and polymorphism
By tester in forum EclipseReplies: 1Last Post: 12-21-2008, 04:58 AM -
what is polymorphism
By Nari in forum New To JavaReplies: 5Last Post: 04-04-2008, 03:14 AM -
what's polymorphism?
By christina in forum New To JavaReplies: 2Last Post: 08-05-2007, 10:29 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks