CodeGym /Java Course /Module 1. Java Syntax /Objects and constructors

Objects and constructors

Module 1. Java Syntax
Level 13 , Lesson 1
Available

1. Creating an object

Well, we've arrived at creating objects. You already encountered this before, but now we will analyze this topic in more detail. It's actually very easy to create objects.

To create an object, you need to use the new operator. Creating an object looks approximately like this:

new Class(arguments)

After creating an object, we most often immediately save a reference to it in a variable, which very often shares the same type as the created object. That means that when creating an object, you usually see code like this:

Class name = new Class(arguments)

Where Class name is the creation of a new variable, and the code to the right of the equals sign is the creation of a new object whose type is Class.

Examples:

Code Note
Object o = new Object();
Create an Object object
Cat pet = new Cat();
Create a Cat object
Scanner console = new Scanner(System.in)
Create a Scanner object

Programmers often name variables after their classes, but with a lowercase letter. For a novice programmer, such code can be confusing:

Code
BufferedReader bufferedReader = new BufferedReader( reader );
Cat cat = new Cat();
PersonInfo personInfo = new PersonInfo()

There is nothing wrong with this code — this is the most ordinary code, in which a variable is created and then immediately initialized by an object of its same type.

To the left of the equals sign we have the creation of a variable. To the right, the creation of an object. That's it.

2. Constructor

You've probably seen that some arguments are frequently passed when creating an object. What's more, arguments are passed for some objects, but not others. How does this whole mechanism with arguments work?

Everything is simple here as well: each class has a special method (or methods) that are responsible for handling arguments passed when creating an object. These methods are called constructors. Or when we're talking about just one: the constructor.

Distinguishing a constructor method from a regular method is easy. This method has two distinguishing features:

  • the name of a constructor is the same as the name of its class (and starts with a capital letter)
  • a constructor has no return type.

In general, here is what it usually looks like:

modifiers Class(arguments)
{
   Code
}

Example:

Code Note
public class Point
{
   public int x;
   public int y;

   Point(int x, int y)
   {
      this.x = x;
      this.y = y;
   }
}
Point class




Point class constructor
public class Solution
{
   public static void main(String[] args)
   {
      Point point = new Point(5, 10);
   }
}




Create an object of the Point class. The class constructor will be called.

Notice what the constructor looks like: it has no return type and its name is the same as the class name.

And one more thing: take a look at the code inside the constructor. The constructor's parameters have the same names as the fields of the class: x and y. It is standard practice to avoid making up novel parameter names. The names are the same as those of the fields of the class. The name conflict is resolved using the this keyword.

3. Calling a constructor

When use the new operator and a command like "new Class(arguments)" to create a new object, two things happen:

  • The Java machine creates an object whose type is Class
  • The Java machine calls the object's constructor and passes in your arguments

As a programmer, you get to decide what constructors your class should have, and what parameters these constructors should have.

Suppose you decide to create a class to keep track of cats at an animal shelter. Then your Cat class might look like this:

class Cat
{
   public String name;
   public int age;

   public Cat(String name, int age)
   {
      this.name = name;
      this.age = age;
   }
}
Cat cat = new Cat("Whiskers", 2);
This is allowed
Cat cat = new Cat("Whiskers");
But this is not allowed This code will not compile.
Cat cat = new Cat();
And this is not allowed. This code will not compile.

The Cat class has just one constructor with name and age parameters. Because there are no other constructors, you must pass the cat's name (name) and age (age) as arguments when creating an object. Passing arguments to the constructor is not optional.

4. Multiple constructors

But if you need to, you can add multiple constructors to the class. There is no limit on the number of constructors or their parameters. When you create an object, the compiler automatically selects the constructor that matches the parameters

Code Note
class Cat
{
   public static final int UNKNOWN = -1;
   public String name;
   public int age;

   public Cat(String name, int age)
   {
      this.name = name;
      this.age = age;
   }
   public Cat(String name)
   {
      this.name = name;
      this.age = UNKNOWN; // Unknown
   }
}
Cat cat = new Cat("Whiskers", 2);
This is allowed: the first constructor will be called
Cat cat = new Cat("Whiskers");
This is allowed: the second constructor will be called
Cat cat = new Cat();
But this is not allowed This code will not compile.

We decided to account for the fact that a cat's age may not be known. To handle this case, we added the special constant UNKNOWN along with a constructor that has just one parameter — the name of the cat.

Note that we still initialize both variables inside both constructors. We replace the unknown/missing parameters with the constant UNKNOWN.

If no value is assigned to the age variable, then it will have the default value of 0. After all, a kitten found on the street may well be 0 full years. That means a zero in the age variable doesn't necessarily mean "unknown age".

5. Default constructor

If you want your objects to be instantiated without any parameters, your class needs to declare a no-argument constructor.

A constructor without parameters is not necessarily a constructor without code. Such a constructor can contain code that initializes variables with starting values:

Code Note
class Cat
{
   public static final int UNKNOWN = -1;
   public String name;
   public int age;

   public Cat(String name, int age)
   {
      this.name = name;
      this.age = age;
   }

   public Cat()
   {
      this.name = "Nameless";
      this.age = UNKNOWN; // Unknown
   }
}
Cat cat = new Cat("Whiskers", 2);
This is allowed: the first constructor will be called
Cat cat = new Cat();
This is allowed: the second constructor will be called

Default constructor

There is a very important point that you should know and remember.

If your class declares not one constructor, the compiler will add a default constructor, which is a no-argument constructor with the public modifier.

But if your class declares even one constructor, then no default constructor will be added and you'll need to add it yourself if you want it.

Code Note
class Cat
{
   public String name;
   public int age;
}
Cat cat = new Cat();
This is allowed: the default constructor will be called

Comments (3)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Wakisa Level 18, Malawi
25 January 2024
The hints have the variable "floorsCount" while instance variable is "floorCount", which gives error unless you match them. (i.e "floorCount" in order for them to match with task conditions)
thompson, braedyn Level 22, United States of America, USA
18 September 2023
cool
Pekotski Level 16, Zurich, Switzerland
1 December 2023
No, it ain't cool. Final is explained in next lesson so why it is used in this?