super()
Suppose I have a class the extends any basic class in the SDK:
publicclass Testextends java.lang.String
{
// constructor
public Test()
{
super();
}
}
What's the difference if I explicitly call super() or not?
Suppose I have a class the extends any basic class in the SDK:
publicclass Testextends java.lang.String
{
// constructor
public Test()
{
super();
}
}
What's the difference if I explicitly call super() or not?
> Suppose I have a class the extends any basic class in
> the SDK:
> public class Test extends java.lang.String
> {
> // constructor
> public Test()
> {
>super();
>
> }
> What's the difference if I explicitly call super() or
> not?
Since you are calling the no-arg super, nothing. The compiler will generate the exact same code. If you need to call a different super then you explicitly call it and the compile will not add any super calls.
Aside: String is final so you cannot exend it.
Not sure what you mean by 'will not add any super calls'
If I do this:
public class Test extends some.sdk.Class
{
// constructor
public Test()
{
super(123);
}
}
do the super() method get called up the chain of some.sdk.Class?
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.
> Not sure what you mean by 'will not add any super
> calls'
>
> If I do this:
> public class Test extends some.sdk.Class
> {
> // constructor
> public Test()
> {
>super(123);
>
> }
>
> do the super() method get called up the chain of
> some.sdk.Class?
See jverd's post - it says it all.