Java programming course: 2.2 Creating objects

This is lesson 2.2 of the Java programming course.


Creating objects

Object instances are created using the new keyword, which is followed by the constructor name[1] and arguments (if applicable). Here is an example where a Date object is created[2]:

[1] Remember that constructors always have the same name as the class in which it is defined.
[2] Date is a Java supplied class that exists in a package called java.util.
Date rightNow = new Date(); // defaults to today's date
 

It is also possible to write the above in two separate statements:

Date rightNow;		// define reference of type Date
rightNow = new Date();	// create new Date object
 

Note how you must specify the type of object that will contain the reference, which in the above case is Date.

Java is a strongly typed language. This means that you need to declare each variable's type and can only store compatible values in that variable.

Object references

In the Date object created above called rightNow, the variable is actually a reference to the object rather than the object itself. You can think of a reference as being a handle or pointer. You can point other references to the same object provided they have the same type:

Date date1 = new Date();
Date date2 = date1; // both date1 & date2 reference the same object

Date date3 = new Date(); // this is a different object
Date date4 = date3; // both date3 & date4 reference the same object

// You now have two objects of type Date:
// - date1 and date2 both reference one of the Date objects
// - date3 and date4 both reference the other Date object

 
Two Date objects each having two references

In the next lesson you will see how to deal with errors in your Java program.

Lesson 2.3 Dealing with errors in Java programs


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Wednesday, 08 April 2026

Captcha Image