Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2011
    Posts
    1
    Rep Power
    0

    Default invoking parent method even though child overrides it...

    Lets say I have 3 classes; A, B & C where B extends A & C extends B
    These classes are Value Objects. When I say C.save(), it should first call save method on A, then on B and lastly on C. In other way, a object before saving its data, should first save its Parent Object data.

    How can we generalize this approach? i tried this, but failed.
    =============================================
    class A{
    boolean hasParent;

    public void save(){
    if(hasParent) saveParent();
    saveMe();
    }

    saveMe(){
    //saveMyData
    }
    }

    class B extends A{
    Data data;

    public B(){hasParent = true;}

    public void saveParent(){
    super.save();
    }

    public saveMe(){
    //save my object data
    }
    }

    class C extends B{
    Data data;

    public B(){hasParent = true;}

    public void saveParent(){
    super.save();
    }

    public saveMe(){
    //save my object data
    }
    }
    ========================
    When I call C.save(), I thought it would call save method on B [which is parent object of C] but it actually calls save method again on C and i get stackoverflow.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,049
    Rep Power
    20

    Default

    B and C don't have their own save() method...do you mean the saveMe() method?

  3. #3
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    Usually this would be done by implementing the 'save()' method in all three classes. Subclass implementations of this method would typically call 'super.save();'. If you need some kind of "saveMe()" method, then you may want to use a different name for each class, like "saveA", "saveB", "saveC". And make the "save me" method private, and maybe also final, to avoid confusion.

Similar Threads

  1. Access Parent and child node
    By emyk in forum Advanced Java
    Replies: 0
    Last Post: 05-02-2011, 11:16 PM
  2. keep child threads running after parent thread dies
    By adammyth in forum Threads and Synchronization
    Replies: 2
    Last Post: 01-27-2010, 01:43 PM
  3. Child-Class Calling a Method in a Parent-Class
    By Blah_ in forum New To Java
    Replies: 5
    Last Post: 09-29-2009, 02:48 AM
  4. Replies: 7
    Last Post: 05-06-2009, 12:42 PM
  5. Parent & Child window issues......
    By jithan in forum New To Java
    Replies: 2
    Last Post: 09-20-2008, 09:21 AM

Tags for this Thread

Posting Permissions

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