Calling Constructors
-
A constructor is a method that initializes an object when it is created.
- The name of the method is the same as the class that it belongs to
and it does not have a return type.
- You get the default constructor by default unless you write another constructor.
- 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, you can include the explicit call to super().