Search code examples
javasubclassingsuper

What is the correct way to initialize a member of a superclass?


if I have a class that has, for instance a HashMap that is initialized in the constructor like so...

public class MySuper{
   HashMap<String,String> foo;

   public MySuper(){
      foo = new HashMap<String,String>();
   }
}

my impression (which is incorrect) is that I just need to call super in the subclass and the same initialization will take place, but Eclipse isn't happy with the following syntax...

 public class MySub extends MySuper{
      public MySub(){
         super.MySuper()
      }
   }

So, I'm curious what the correct way to do this is. Do I have to create a separate method in MySuper that does the initialization and call super on that? (I know that will work), but I was under the impression that there was a way to just call super on the class I'm extending from and have it do whatever it would normally do in its constructor.

TIA


Solution

  • you can just call super() -- also, fyi, in your particular example, you don't even have to write a constructor in the sub-class, it will implicitly call the super class default constructor