Calling super in subclasses

Is there a pattern to accomplish the following?
I have a setup() method that must be called:
class A {
  public void setup() {
    // necessary code for A
}I want to ensure its code gets executed even if a subclass overides it. The usual way is with a "hook":
class A {
  public final void setup() {
    // necessary code for A
    onSetup();
  public void onSetup() {}
}This way, a subclass can only override onSetup(), ensuring that the code in setup() gets called. However, say I want to play the same trick with subclasses of A:
class B extends A {
  public final void onSetup() {
    // necessary code for B
    onOnSetup();
  public void onOnSetup() {}
class C extends B {
  public final void onOnSetup() {
    // necessary code for C
    onOnOnSetup();
  public void onOnOnSetup() {}
}Is there a pattern I can use so that each class only has to override a method called setup(), and it is guaranteed that the code in every overidden setup() method will be called? Calling super() from within each setup() is fragile, because a subclass might forget it. Using a hook each time (as in the above example) is annoying, because each time, a different name must be assigned to the non-final method at every level in the hierarchy.

I have dealt with this. In keeping with the principle of not calling overridable methods in constructors, one may require such a method. For instance, I have objects that are ultimately part of a database, but when created they do not have the db object yet. So later they must be setup with the appropriate db object.
I think it is understood that overriding a method involves respecting the class you are altering. You should not override a method if you do not understand what it does. That being said, the solution here is to simply put in the comment of the method that it must always be called by any subclasses. There are lots of things which can not be forced. If one overrides this method but does not call super, they are violating the contract of the class.
You can add a private boolean isSetup, and assert if any methods are called before isSetup is true, if you wish. Personally I would throw an IdiotException :-)
If you have time to burn and want to get buck wild, you can also use the strategy pattern.
class AClass {
  private List setupers = new ArrayList();
  AClass(){
     Setuper su = new Setuper() {
          public void setup() {
               //do setup for AClass
      setupers.add(su);
  public final void setup(){
      for(Iterator it = setupers.iterator();it.hasNext();){
         ((Setuper)it.next()).setup();
       setupers = null;
class BClass extends AClass {
  BClass(){
     Setuper su = new Setuper() {
          public void setup() {
               //do setup for BClass
      setupers.add(su);
interface Setuper {
    public void setup();
}But once you start down this road, you will eventually come face to face with the fact that some things are understood and a certain amount of intelligence, no, respect is required to extend a class properly. There will always be a way to force the issue, but it will involve increasing amonts of work with little pay off. You cant save people from themselves.

Similar Messages

  • Initialize fields prior to calling super() possible?

    Problem: I referece an object in a subclass method which overwrites a superclass method. The object is initialized in the constructor of the subclass. However, I need to initialize the superclass first by calling super(). The superconstructor calls the overwritten method leading to an NPE in the overwritten method because the object has not been initialized yet. Are there patterns that avoid testing the object to be not null every time the overwritten subclass method is called?
    Thanks
    fatzopilot

    paul.miner wrote:
    jtahlborn wrote:
    this is a very bad design. a class should never call a method in its constructor which can be overridden in a subclass. the behavior in this situation is "undefined" according to the JLS, and should be avoided at all costs.I agree this is bad design, but I don't think the behavior is undefined. I think the behavior is that the subclass method will see that subclass' fields in their uninitialized state, which do have defined values (int's are 0, booleans are false, references are null, etc). Are you sure this is in the JLS?you're right, i went back and looked at the JLS (12.5 in the third edition for those following along at home). method dispatch is specified to work consistently during constructor invocations (for some reason i remember it being undefined). regardless (we both agree here), it is a terrible design, because the subclasses methods are being executed before that class is initialized.

  • Error in calling Super() method cannot reference ...

    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class MyFrame extends JFrame {
    String St="Rayudu";
         JPanel jp1= new JPanel();
         JButton jb1=new JButton("Hello");     
    public MyFrame() {
    super("Document :" + St);
              jp1.add(jb1);
              getContentPane().add(jp1);
    //...Then set the window size or call pack...
    setSize(300,300);
    //Set the window's location.
         setLocation(300,300);
         setVisible(true);
    public static void main(String ar[])
    MyFrame mf=new MyFrame();
    mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    C:\java>javac My*.java
    MyFrame.java:11: cannot reference St before supertype constructor has been called
    super("Document :" + St);
    ^
    1 error
    Can anyone explain?
    thanks in advance.

    Change your constructor to take an argument of type String, pass this along to the super method when you call the new instance of your class in main. ie:
    public myFrame( String title ) {
    super( "Document: " + title );
    st = title; //if you need it in that String Object assign it here.
    //etc...
    public static void main( String args[] ) {
    new myFrame( "Testing" );
    Does this answer your question?

  • Why Do We Have To Call super.init(config); in init() method of servlet?

    Hi, everyone..
    I wonder why we call super.init(config) in init method of servlet... If i dont call it ; when i try to get servletcontext in service method it throws java.lang.NullPointerException...when we call super.init() , what is happening behind the scene? If anybody has a technical explanation for my question , i will be very pleased...
    THX FOR YOUR FUTURE REPLIES IN ADVANCE....

    I am sorry about the uppercases and i dont want to seem smart on java forums... Anyway, m8 this is the thing that i know... i meant; for instance when we override doGet or doPost method ; we dont need to override init method; but the server loads the servlet and we can get the context of the servlet in these methods easily by calling getServletContext() method; however when we want to call service method implicitly by jndi, servlet needs to be loaded and init method must call its parent...(i also write down in web.xml <load-on-startup>.... for that servlet).
    thx for your replies in advance....

  • Call super- super- method( )?

    I have a class CL_LION that inherits from CL_CAT which inherits from CL_ANIMAL.
    In CL_ANIMAL, I have a method shout( ), which is overwritten in each of the children.
    Now, I want to call super->super->shout() from CL_LION (which means I want to skip the shout() of CL_CAT and directly call shout() of CL_ANIMAL.
    The syntax "super->super->shout() does not work.
    Is there another way to do this?
    Best regards,
    Daniel

    Ok, so you want to go directly back to the animal class.  How about we use an INTERFACE.
    report zrich_0001.
    *       INTERFACE lif_animal
    <b>interface lif_animal .
      methods shout.
    endinterface.</b>
    *       CLASS lcl_animal  DEFINTION
    class lcl_animal definition.
      public section.
    <b>    interfaces lif_animal.</b>
        methods: shout.
    endclass.
    *       CLASS lcl_animal IMPLEMENTATION
    class lcl_animal implementation.
      method shout.
        write:/ 'This is an animal shouting'.
      endmethod.
    <b>  method lif_animal~shout.
        write:/ 'This is an animal shouting'.
      endmethod.</b>
    endclass.
    *       CLASS lcl_cat DEFINITION
    class lcl_cat definition inheriting from lcl_animal.
      public section.
        methods shout  redefinition.
    endclass.
    *       CLASS lcl_cat IMPLEMENTATION
    class lcl_cat implementation.
      method shout.
        call method super->shout( ).
      endmethod.
    endclass.
    *       CLASS lcl_lion DEFINITION
    class lcl_lion definition inheriting from lcl_cat.
      public section.
        methods shout  redefinition.
    endclass.
    *       CLASS lcl_lion IMPLEMENTATION
    class lcl_lion implementation.
      method shout.
        call method super->shout( ).
      endmethod.
    endclass.
    data: a_lion type ref to lcl_lion.
    data: a_animal type ref to lcl_animal.
    <b>data: if_animal type ref to lif_animal.</b>
    start-of-selection.
      create object a_lion.
    <b>  if_animal ?= a_lion.
      call method if_animal->shout( ).</b>
    Regards,
    Rich Heilman

  • Why to Call super()

    Suppose I have a class named Class1. Another class extends Class2 which extends Class1.
    class Class1{
    Class1(){
    class Class2 extends Class1{
    Class21(){
    super()//Why this.. Any way, super constructor is being called no??
    We sometimes call super() in the constructor of the sub class to invoke the Super Class constructor. Now, my question is, Whenever we make a new instance of a class, it is any way going to call the super class constructor as per the basic Java design. Then Why, we sometimes call super() specifically.. ???
    Thanx in Advance..
    Naren

    When java calls the super class constructor, it calls the no argument
    constructor.One reason to call the constructor is if the class was
    designed without a no argument constructor. You would get an error
    if you extended it and didn't call its constructor.You may also want to
    call a different constructor instead of the default one.

  • Sub class   calls super in constructor

    when a sub calss calls super() in its constructor is it overriding the constructor of base class ?
    Class A {
    A(Strin neme){
    class B extend A{
    B(){
    super("test")
    Systemout......
    I donot know the term explaning this feature is it called overriding constructor?

    miro_connect wrote:
    so how to describe this code, are there any terms to explain this methodology to not technical guys ?Yeh. "Magic". Seriously. There's little point explaining such things to non-technical people. Ever tried to teach your mum how to program a VCR?
    By definition, non-tech people will simply not understand what you're on about, and won't need to.

  • Calling super.myOverriddenMethod() using reflection

    I have a method in a super class that doesn't do all I want it to do; so I need to do something like this:
    protected void myOverriddenMethod(Object param)
        super.myOverriddenMethod( param );
        doExtraNeededBit();
    }But I need to do this in a plugin class that works with 2 code lines
    The earlier superclass does not have this method, and so I can't call super.myOverriddenMethod( param );
    I have tried using reflection like this
    protected void myOverriddenMethod(Object param)
        //super.myOverriddenMethod( param );
        try{
           Class mySuperclass = Class.forName( "myPackage.MySuperClass" );
           Method overriddenMethod = mySuperclass.getDeclaredMethod("myOverriddenMethod",new Class[]{Object.class});
           overriddenMethod.invoke(this, new Object[]{ param ) });
      }catch(Exception e){e.printStackTrace();}
        doExtraNeededBit();
    }but this does not work, I get a StackOverflowException as the super method isn't being called, this method is calling itself...
    How do I get it to call the super method instead, eg something like
           overriddenMethod.invoke(super, new Object[]{ param ) });Which doesn't compile....

    So why can't you use super.myOverriddenMethod(Object
    param) ?
    What I understood from that is you are trying to call
    a method in the superclass, but the compiler won't
    let you because, as you say, the method doesn't
    exist. I hope that isn't right...thats right!
    in one code line the method exists - the earlier one doesn't have it
    You can normally use reflection to see if a superclass method exists, and call it if so (I only want to call it if it exists). But I don't know how to call a superclass method that you are overriding using reflection

  • When overriding methods, should i call super at the begining or end

    Hi,
    when overriding methods such as swing's dispose(), and removeNotify(), should i call the super methods at the begining of the method or at the end?
    or does it make a difference....i was under the assumption i should call it at the end, that way i can do whatever necessary things i needed, then call the default....

    In cases where it truly doesn't matter, I think people tend to call super first. If I see it done some other way, it's an indicator that something unusual is going on. I'd liken calling super at the end of a method to iterating through an array in reverse inside of a 'for' loop. One can adopt either convention but people may get confused if you pick the less common one for no particular reason.

  • Calling super.method() from anonymous class

    Look at this:
    class SynchronizedListModel
      extends DefaultListModel
      public void addElement(Object obj)  {
            final Object fObj = obj;
            Runnable rAdd = new Runnable()
                public void run() {
                    super.addElement(fObj);
            if (SwingUtilities.isEventDispatchThread())  {
                rAdd.run();
            } else {
                SwingUtilities.invokeLater(rAdd);
    }super in super.addElement(fObj); does not reference the addElement(obj) method of the DefaultListModel but of Object. So the compiler throws an error.
    How can I call the addElement method of DefaultListModel in the inner Runnable-class?
    Thanks for your help
    Ulrich

    I use a more compact semi-recursive form
        class SynchronizedListModel
        extends DefaultListModel
            public void addElement(final Object obj)
                if (SwingUtilities.isEventDispatchThread())
                    super.addElement(obj);
                else
                    SwingUtilities.invokeLater(new Runnable()
                        addElement(obj);
        }This is not true recursion because call the to addElement() is done in the Swing event thread not in the calling thread.

  • Is there a way to allow DLLs to call sup-application in TestStand?

    Hi,
    I've got a TestStand sequence that calls a DLL function which is generating an EAccess Violation.
    Now this particular function seems to run two seperate sub process of some kind. I can't figure out what they are, but when I run the DLL function in a CVI environment, two items appear on my windows taskbar and then disappear just prior to the function finishing successfully.
    I've been told that TestStand likes to control its environment... my current theory is that the error generated in TestStand during the funciton call has something to do with the function attempting to launch a thread (or some kind of application) and TestStand not allowing it to do so. Is there a way to let the function run mul
    tiple threads without TestStand's permission? Or turning off TestStands control for one step? Or something to that effect?
    I've tried making a DLL wrapper for the DLL function... but it has the same effect since a sub-thread is trying to be created.
    Thanks,
    Marek D.

    Hi Marek D,
    This question appears to be related to another post that you and I were working on before. Does this post -> http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RPAGEID=135&HOID=50650000000800000040520000&UCATEGORY_0=_8_&UCATEGORY_S=0 <- have anything to do with what you are asking now? If it does did you try the suggestion that I mentioned last in the other thread? Your use of the dll in TestStand does not follow the exact same pattern as what you demonstrated in CVI, and this would be a good starting point.
    To answer your question though, no, TestStand does not have a problem with a dll that it loads and invokes functions on trying to spawn new threads. This is a rather common scenario in fact. As I stated before it appears that since th
    e dll is loading fine and TestStand is able to access its functions ok, there is not really a problem with how TestStand interacts with the dll. In fact if there were a specific problem dealing with this dll trying to create additional threads there could indeed be a problem in that its threads are not being managed properly from within inside the dll itself. Trying to guess at how the dll operates is generally a timewaster, unless you know its exact requirements you may never be able to get it to work. It appears that there is either an external dependency you are not taking into account with this particular dll or you are using it improperly in TestStand. Trying my previous suggestion of trying to reproduce the CVI setup exactly is your best bet.
    Jason F.
    Applications Engineer
    National Instruments
    www.ni.com/ask

  • Can we call super class method from Overwrite method using SUPER keyword

    Hi All,
    For one of our requirement , I need to overwrite "Process Event" method of a feeder class  ,where process event is present is protected method. so when we are making a call , then its saying
    "Method  "process event"  is unknown or Protected  or PRIVATE ".
        But we are just copied the source code in the "Process Event" method to the Overwrite method.
    Can anyone provide me the clarification , why system behaving like this.
    Thanks
    Channa

    Hi,
    I think you can not.
    Because, only public attributes can be inherited and they will remain public in the subclass.
    for further detail check,
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    regards,
    Anirban

  • Extending object, without calling super constructor

    public class Object1
        byte index;
        public Object1(byte i)
            index = i;
    public class Object2 extends Object1
        private byte j;
        public Object2() {
            super((byte) 0);
        public void setIndex(byte i)
            j = i;
    import java.util.*;
    public class Test1
        private ArrayList<Object1> aList;
        public Test1()
            aList = new ArrayList<Object1>();
        public void run()
            for (byte i = 0; i < 10; i++)
                aList.add(new Object1(i));
        public ArrayList<Object1> getResults()
            return aList;
    import java.util.*;
    public class Test2
        ArrayList<Object1> results;
         * Constructor for objects of class Test2
        public Test2()
            Test1 t1 = new Test1();
            t1.run();
            results = t1.getResults();
        public void run()
            Iterator<Object1> i = results.iterator();
            while (i.hasNext())
                Object2 o2 = (Object2) i.next();
    public class Test3
        public static void main(String[] args)
            Test2 t2 = new Test2();
            t2.run();
    }There are two things with this code that I'm having problems with.
    1. I want to create an object of class Object1 in Test1. That works fine. In Test2 I then want to extract the object from the ArrayList, but since Object2 extends Object1, I want to get an Object2 out from the ArrayList. However with the code above, I get a ClassCastException. If I leave out the cast, I get an incompatible types error.
    2. I want Object2 to be an extension of Object1, that is, with more fields and methods. But I have no need to create an object of class Object2, since I know I already have an ArrayList of Object1. So I want to remove the constructor from Object2, seeing as I won't need it. However, if I remove the super part (which, again, is not needed, as I will already have created my needed objects of class Object1 when I get there, and only need to EXTEND my Object1 objects), I get a cannot find symbol, constructor Object1() error.
    I'm not sure that I can solve problem 2 without using a super. But I am convinced that I must be able to get the Object1 objects out as Object2 instead. I would just like some help with how to do that.

    ThemePark wrote:
    But I am convinced that I must be able to get the Object1 objects out as Object2 instead. I would just like some help with how to do that.Maybe you don't understand how inheritance works. Go read a basic tutorial on inheritance. You can use an Object2 as an Object1, but not an Object1 as an Object2. You either have to create Object2 objects in the first place; or have to make a wrapper class that takes an Object1 and passes things to the Object1 object; and use objects of this wrapper class.

  • Constructor of derived-class has to call constructor  of super-class?

    In java, constructor of derived-class has to call constructor of super-class? there is no way to omit this step?

    Correct. If you do not explicitly call the constructor, a call to the no-arg c'tor, super(), is automatically inserted.
    It would be a mess to have it any other way. You'd be creating objects that are not completely initialized. They'd be in an invalid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Call to super must be first statement

    I'm new to Java and I have a question regarding super(). I'm implementing a design where we have a custom exception which extends Exception. The design calls for null messages to lead to throwing an IllegalArgumentException, but Exception's constructor does not throw an IllegalArgumentException for a null message.
    Here is what I want to do, but not allowed to since super must be the first statement in the constructor:
    public CustomException(String message) {
        if (message == null) {
            throw new IllegalArgumentException("message cannot be null.");
        super(message);
    }I could call super first and then throw an exception if the message is null, but that doesn't seem like a good solution.

    public CustomException(String message) {
        super(nullCheck(message));
    static String nullCheck(String message) {
        if (message == null) {
            throw new IllegalArgumentException("message cannot be null.");
        return message;
    }

Maybe you are looking for

  • Trouble downloading movies due to "authorizing" error

    I am having trouble downloading video content from iTunes.  I get the error message that states that the computer is not authorized.  I went ahead and deauthorized all 5 computers that are associated with my account, and then reauthorized the compute

  • Cannot (re-)install itunes (64) for windows 8. get error 7 (Windows error 193)

    I've used itunes for itunes for quite some time before making some hardware change (cpu and motherboard).  The OS, like before, is Windows 8. But now each time that I try it seems to install up to and including the final "finish" in the process.  Aft

  • Problems in viewer

    I have problems in viewing my clips in continuous mode in the viewer. The first two seconds work, but after that its all jagged until video stops after 5-6 seconds and only audio continues!

  • Master and Preview

    Not sure what ive done but i can no longer get the master and preview image at the same time on the filmstrip or viewer. probably something simple i know but. v2.1.4

  • Converting Forms 3.0 to Web Forms

    Hi, Can I use f60cmp.exe for converting Forms 3.0 INP files into *.fmb files? if yes, Could you also please tell me that what are all necessary steps to be taken for making the form as a web based form. Thanks in advance, Muthu