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]:
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
In the next lesson you will see how to deal with errors in your Java program.
Comments