Results 1 to 3 of 3
- 02-25-2011, 07:05 AM #1
Member
- Join Date
- Feb 2011
- Posts
- 4
- Rep Power
- 0
A question about inheritance / polymorphism
Hi, i tried the following code:
In the last two lines doSomething(Parent) is called, but i want it to act like a virtual function, to activate the right overloaded function depending on the parameter run-time type. I know i can define doSomething() in Parent, FirstChild and SecondChild classes and it should work, but it's important that it will be in Other class. Is it possible?XML Code:<pre> public class Parent { } public class FirstChild extends Parent { } public class SecondChild extends Parent { } public class Other { public void doSomething(Parent obj) { // some code } public void doSomething(FirstChild obj) { // some code } public void soSomething(SecondChild obj) { // some code } } public class Another { public static void main(String args[]) { other = new Other(); Parent first = new FirstChild(); Parent second = new SeconChild(); other.doSomething(first); other.doSomething(second); } } </pre>
- 02-25-2011, 07:43 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,413
- Blog Entries
- 7
- Rep Power
- 17
Overloading is a compiler issue; all that the compiler knows is that your variables first and second are Parent objects (it doesn't think much further) so it calls the method that takes a Parent parameter. Maybe the Visitor pattern (also called the Double Dispatch pattern) can be of help, i.e. your other class is the Visitor and calls a Parent object that calls the correct method in your Visitor again according to its real type.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-26-2011, 11:53 AM #3
Member
- Join Date
- Feb 2011
- Posts
- 4
- Rep Power
- 0
Similar Threads
-
Still trying to grasp Polymorphism and Inheritance
By tashimoto in forum New To JavaReplies: 15Last Post: 12-06-2010, 08:35 PM -
Question involving Polymorphism, inherticance, casting...
By myst in forum New To JavaReplies: 45Last Post: 05-25-2010, 08:32 PM -
question about polymorphism
By becky in forum New To JavaReplies: 4Last Post: 02-11-2009, 10:59 PM -
inheritance and polymorphism
By tester in forum EclipseReplies: 1Last Post: 12-21-2008, 04:58 AM -
Relation between Polymorphism and Inheritance
By janakiram.attuluri in forum Advanced JavaReplies: 1Last Post: 12-26-2007, 11:32 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks