1. Exam Points
Call a constructor by passing into the correct arguments.Default values of different data types when calling the default constructorof a class.- All the
constructorsin this course will be declaredpublic.- For a
parameter of a reference type,pass into an objectof that type.- It is
good practice to declare attributes as private, and then addpublic methods to access them.
2. Knowledge Points
(1) Constructors
- A
constructoris a special method inside a class. - A class contains constructors that are
called to create objects. About constructors:- A constructor has the
same name as the classin which it is declared. - A constructor has
no return type. - A constructor is
called when an object is created. - A constructor
can be overloaded(重载), meaning there can be multiple constructors with different signatures inside a class. - The
purposeof a constructor: to initialize attributes or do other initialization work. - A constructor sets the initial state of an object but setting initial values to its attributes.
- A constructor has the
- Example:
(2) The Default Constructor
- When
no constructor is written, Javaprovides a no-parameter constructor, and theinstance variables are set to default valuesaccording to the data type of the attribute. This constructor is called thedefault constructor. The default values are:- int attribute: 0.
- double attribute: 0.0.
- boolean attribute: false.
- reference type (ex. String): null.
- The default constructor is gone if you declare any constructor.
(3) Pass Arguments(实际参数) to Parameters(形式参数)
- For a parameter of a
primitive type, pass into avalueof that type. - For a parameter of a
reference type, pass into anobjectof that type.