(i.e. is calling super()
the same as calling this()
, but for calling the parent class?).
Does calling super(...)
affect fields/methods of a subclass, like calling this(...)
would?
E.g., for:
class SuperClass {
private boolean solid;
public String name;
public SuperClass(boolean solid, String name) {
this.solid = solid;
this.name = name;
}
}
class SubClass {
public SubClass(boolean solid, String name) {
super(solid, name);
}
public SubClass(boolean solid) {
super(solid, "");
}
public SubClass(String name) {
super(false, name);
}
}
and had SubClass sc = new SubClass(true, "MyEntityPrototype");
, would the fields solid
and name
be changed for sc
?
Thanks!
Cheers!
Cheers!
Top comments (4)
A subclass has all the characteristics of the superclass (all that it can access, anyway, so anything but
private
), plus everything it defines for itself.So, your Subclass could be defined as:
and it would work in the exact same way.
When you create an instance of the subclass, it also is an instance of the superclass, too, so you have everything that is defined in both. It is only one and the same instance, though. You must call the
super()
constructor first not because the super class is something separate, but because you must be sure to initialize the state of the superclass first, and then do the rest of the subclass initialization.I hope this clears your doubt. Happy learning!
It didn't fully. Does thid leab towards yes, or no?
That's a yes. Because it's the same instance.
super()
does not target another instance, it just sets up the part of your instance that is defined in the superclass.Your
sc
variable is not two separate instances, one ofSuperClass
and one fromSubClass
: it is just one instance ofSubClass
, where a part of the state is made from allSuperClass
defines. You must callsuper()
as first thing in the subclass constructor (your code won't compile otherwise) because you must first initialize the part the instance inherits, and only after that you can go on initializing the part that the subclass defines.Is this clearer?
Yes. Thank you.
Though, final question, will it not compile if I don't call
super()
at all?