3.4 Constructors

0 阅读1分钟

1. Exam Points

  • Call a constructor by passing into the correct arguments.
  • Default values of different data types when calling the default constructor of a class.
  • All the constructors in this course will be declared public.
  • For a parameter of a reference type, pass into an object of that type.
  • It is good practice to declare attributes as private, and then add public methods to access them.

2. Knowledge Points

(1) Constructors

  • A constructor is a special method inside a class.
  • A class contains constructors that are called to create objects. image.png
  • About constructors:
    • A constructor has the same name as the class in 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 purpose of 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.
  • Example:
    image.png
    image.png

(2) The Default Constructor

  • When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default 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 a value of that type. image.png
  • For a parameter of a reference type, pass into an object of that type. image.png

3. Exercises