Java · Beginner level

Beginner level · Module 4: Classes and Objects in Java · Lesson 2 of 3

Constructors and the this Keyword

Give objects valid starting values with constructors, use this to refer to the current object, and know when to use static.

In this lesson you will

  • Write constructors, including overloaded ones
  • Use this to distinguish fields from parameters and decide when a member should be static

Key concepts

constructorthisconstructor overloadingstatic members

The lesson

A constructor runs when an object is created and sets its starting state: public Product(String name, double price) { this.name = name; this.price = price; }. this.name means the object's field, while name on its own means the parameter.

You can provide several constructors with different parameters, and one can call another with this(...). If you write no constructor, Java provides an empty one; as soon as you write one, the empty default disappears.

A static field or method belongs to the class, not to any one object. A counter of how many products have been created is static; each product's price is not. Calling an instance method from static main requires an object.

Step by step

  1. Add a constructor to Product that sets name and price.
  2. Add a second constructor that sets only the name, with price 0.
  3. Add a static counter that increases in every constructor.
  4. Create several products and print the counter.

Practice activity

Write a BankAccount class whose constructor requires the owner's name and an opening deposit, with a static count of accounts opened.

Expected result: Accounts are created only with an owner and deposit, and the static count matches the number created.

Check your understanding

  1. What does this.price = price; do?

    Show answer

    It copies the parameter price into the current object's field price.

  2. Should a count of all objects created be static?

    Show answer

    Yes. It belongs to the class as a whole, not to one object.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.