Results 1 to 2 of 2
  1. #1
    viking90 is offline Member
    Join Date
    Apr 2010
    Rep Power

    Default Overriding methods - design problem

    I have the following code:
    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(); }
    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".
    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?

  2. #2
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    London, UK
    Blog Entries
    Rep Power


    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

  1. Design Problem
    By crystalClear in forum Advanced Java
    Replies: 3
    Last Post: 02-09-2011, 12:02 PM
  2. Netbeans 6.8 GUI design problem
    By newbiejava in forum NetBeans
    Replies: 0
    Last Post: 01-14-2010, 02:02 AM
  3. Overriding Methods
    By AndrewM16921 in forum New To Java
    Replies: 2
    Last Post: 09-23-2009, 06:26 AM
  4. design? return output within methods
    By jon80 in forum New To Java
    Replies: 1
    Last Post: 06-08-2009, 07:22 AM
  5. Java Design Problem
    By hencre in forum Advanced Java
    Replies: 2
    Last Post: 02-25-2009, 07:08 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts