By Tony Bevis on Saturday, 07 October 2023
Category: Java

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.

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

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:

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

Related Posts

Leave Comments