Results 1 to 2 of 2
- 03-23-2011, 08:25 PM #1
Member
- Join Date
- Apr 2010
- Posts
- 6
- Rep Power
- 0
Overriding methods - design problem
I have the following code:
I wanted to make, that when an instance object of the C class calls the getInfo() method, it returns "ccc", and when it calls getAllInfo(), it returns "aaabbbccc".Java Code:class A { String getInfo(){ return "aaa"; } String getAllInfo() { return getInfo(); } } class B extends A { String getInfo(){ return "bbb"; } String getAllInfo(){ return super.getAllInfo() + getInfo(); } } class C extends B { String getInfo(){ return "ccc"; } String getAllInfo(){ return super.getAllInfo() + getInfo(); } }
However, it doesn't work as intended - it returns "ccc" and "ccccccccc" respectively. I found out, the problem is when the C object calls the getAllInfo() method, all of the resulting calls to the super.getInfo() method return "ccc", as specified in C class (due to polymorphism). But i do not want to apply polymorphism here. I tried also to typecast the object to the respective class, for example ((B) this).getInfo(), but it still performs the overridden method of C.
How should I solve this? I feel the problem lies somewhere in bad design of these methods. All I wanted is to make the getInfo() return only "info" of self, and the getAllInfo() return all the infos from the parent classes upwards. Can you help me?
-
getAllInfo cannot get strings "aaa" or "bbb" from C because those strings are not stored, and then the method that creates them is the one you are over-riding.
i think the best way to fix this is to introduce a class field to hold the class string "aaa" or "bbb" or "ccc". and then the getInfo method will call the field.
the other thing to do is rewrite the getAllInfo method to return super.getInfo + getInfo
Similar Threads
-
Design Problem
By crystalClear in forum Advanced JavaReplies: 3Last Post: 02-09-2011, 12:02 PM -
Netbeans 6.8 GUI design problem
By newbiejava in forum NetBeansReplies: 0Last Post: 01-14-2010, 02:02 AM -
Overriding Methods
By AndrewM16921 in forum New To JavaReplies: 2Last Post: 09-23-2009, 06:26 AM -
design? return output within methods
By jon80 in forum New To JavaReplies: 1Last Post: 06-08-2009, 07:22 AM -
Java Design Problem
By hencre in forum Advanced JavaReplies: 2Last Post: 02-25-2009, 07:08 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks