More on Constructors
-
Remember, a constructor is a method that initializes an object when it is
created and the name of the method is the same as the class that it belongs to.
- You can call a constructor from inside of another one by using this
as a method name:
this(arg1, arg2, ...);
- When you create a constructor in a subclass, you will usually want to
call the constructor in the superclass so that any inherited instance variables
are initialized properly.
- Use the keyword
super:
super(arg1, arg2, ...);
- This must be the first statement in your method.
- If you don't explicitly use super to call one of the superclass's
constructors, it will automatically call super() for you.
- While you are learning, it is not a bad idea to include the explicit call,
even if it is the default, so that is is clear what constructor is
being called in your subclass.
- After you have learned it, take the explicit calls to super() out.