开发者

Calling super()

When do you call super() in Java? I see it in some constructors of the derived class, but isn't the constructors for each of the parent class called automatically? Why would you nee开发者_开发技巧d to use super?


If you provide a class like this:

public class Foo
{
}

or this:

public class Foo()
{
    public Foo()
    {
    }
}

the compiler will generate code for this:

public class Foo()
{
    public Foo()
    {
        super();
    }
}

So, strictly speaking, the call to "super()" is always there.

In practice you should only call "super(...)" where there are parameters you want to pass to the parent constructor.

It isn't wrong to call "super()" (with no parameters) but people will laugh at you :-)


You would need to use super() in a case like this:

public class Base {
   public Base(int foo) {
   }
}

public class Subclass extends Base {
   public Subclass() {
      super(15);
   }
}

This is a very contrived example, but the only time that you need to call super() is if you're inheriting from a class that doesn't provided a default, parameterless constructor. In this cases you need to explicitly call super() from the constructor of your subclass, passing in whatever parameters you need to satisfy the base class's constructor. Also, the call to super() must be the first line of your inherited class's constructor.


There is no need to call super().

From Accessing Superclass Members :

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.


As has been said, if your constructor does not explicitly call super() with or without some argument, java will automatically call the default constructor of the superclass.

However, explicitly calling super() is just that--explicit. If you know the superclass's constructor does something significant, it's a useful reminder to whomever is maintaining your code that super() is being called first (and may have side effects). This might even be a useful spot to put a breakpoint while debugging.


If you fail to call super in a constructor, then the compiler will add a no-argument super call as the parent constructor for the first line of the constructor body.

So as in the previously posted code

public class Foo
{
}

or

public class Foo
{
  public Foo()
  {
  }
}

the compiler will generate code that aligns with the rules of Java. All objects are subclasses of java.lang.Object, so the compiler will compile it as if it was written

// All classes extend Object.  This is Java, after all.
public class Foo extends java.lang.Object
{
  public Foo()
  {
    // When constructing Foo, we must call the Object() constructor or risk
    // some parts of Foo being undefined, like getClass() or toString().
    super()
  }
}

But if the super class doesn't have a constructor that matches the parameters, then you must call the appropriate non-matching super class constructor.

public class LightBlue extends java.awt.Color
{
  public LightBlue()
  {
    // There is no Color() constructor, we must specify the suitable super class
    // constructor.  We chose Color(int red, int green, int blue).
    super(172, 216, 230);
  }
}

Other times, perhaps there is a constructor that matches the signature of the sub class's constructor, but for whatever reason, you do not wish to pass the parameters directly to the super class constructor.

public class HSVColor extends Color
{
  public HSVColor(int hue, int saturation, int value)
  {
    super(...code converting HSV to Red...,
          ...code converting HSV to Green...,
          ...code converting HSV to Blue);
  }
}

If you neglect to explicitly specify the super class constructor, then the compiler adds in the default no-arg super class constructor. However, if that constructor doesn't exist, then the compiler will not compile the class, because it is unclear which of the exposed constructors is the correct one to call.

It is a style consideration, but you may decide to always include the super() call. If you chose to do so, it will be because you want the remind the reader that the base class objects must be built as part of the sub class object, and you want to make the particular super class constructor explicit. Traditionally, an always included super() call is quite odd, since traditionally code is only typed out if it differs from "default" behaviour.


When you have a class that extends another class and the father class have no default constructor then you have to use super() in the Son's constructor to call the constructor in the Father Class with the proper arguments like this :

class A
{   
    int a; 
    A(int value) 
    {
      this.a=value; 
      System.out.println("A Constructor " + a ); 
    }
}

class B extends A
{ 
    int b;
    B()
    {
      super(5);
      this.b=10; 
      System.out.println("B Constructor " + b); 
    } 

}

you have to know that yo can't use "super" with "this" if you want to call another constructor in the calss using "this".


I wanted to provide some information that hasn't been mentioned so far. If you use a call to this(...) in a constructor, then you can't have a call to super(...); This also includes Java's automatic insertion of the parameterless call to super();

The following example illustrates this point, including explanatory comments:

public class B extends A {
    private int x;

    public B() {
        // Java doesn't call super(); here, because 
        // of the call to this(...); below.
        // You can't call super(...) here either,
        // for the same reason.

        this(42);  // Calls public B(int x) below.
    }

    public B(int x) {
        // Java does call super(); here.
        // You can call super(...) here, if you want/need to.
        // The net result of calling new B() above is that
        // super(...) for class A only gets called once.

        this.x = x;
    }
}


super() is implicit when no other class/superclass constructor is called.


You may call super() with parameters if you want to call a non-default constructor of the superclass, or if the superclass does not have a default constructor. The compiler can only insert the default, no arguments super() constructor.


Because the super class' constructor is not called automatically. There might, for example, be several constructors, some of which take additional parameters. So you do not always have got an "empty" super() statement, but something like this:

public class DerivedClass extends SomeOtherClass
{
   private String anotherParameter;
   public DerivedClass(int parameterA, String parameterB, String anotherParameter)
   {
     super(parameterA, parameterB);
     this.anotherParameter = anotherParameter;
   }
}

Edit: I obviously forgot to say (or my choice of words simply wasn't good, but I'm no native speaker, sorry for that) that if the super class does not take any parameters, the call to super() will be done for you by java/the compiler. (Now that I re-read my answer, I can see that it really sounds like you would always have to call super().)


Although super() does nothing functionally for the compiler (the superclass default constructor is called automatically), it certainly does a lot for me. It says to me: "Do not remove the empty constructor. It's there for a reason".

A perfect example is where you create Spring managed beans or JPA Entities and you've created a parameterized constructor.

@Entity
public class Portfolio {

    ...

    public Portfolio() {
        super(); // This says to me: DON'T DELETE!
    }

    /**
    *  Because there is now a parameterised constructor (me), 
    *  the default constructor no longer exists. This means
    *  that for this example, you need an empty constructor in place (above) 
    **/
    public Portfolio(String name) {
        this.name = name;
    }
}


Super is called when we want to inherit some of the parameters from the parent class. It is not compulsory as the compiler always call the default constructor. If you want to inherit a constructor having some parameters then you need to call the super. So you can use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜