i

JAVA Complete Course

Creating an Object

We have already touched shortly how to initialize and declare objects from classes in Java. There are few ways of objects declaration

One of them is declaration/initialization object with constructor and new keyword.

This example declares class City with two properties: name and population. Also City class has only one constructor (with two arguments). In constructor we are initializing class variables with passed values. In main method, we are creating new object and variable name is newYork. Before actual City class constructor is called, name and population properties were holding default values: name = null and population = 0.

Let’s review a bit advanced way of creation actual instance of class. It is done with newInstance() method call which is actual method of Class (this is not the class you created, it is from Java). If we know the name of the class & if it has a public default constructor we can create an object –Class.forName. We can use it to create the Object of a Class. Class.forName actually loads the Class in Java but doesn’t create any Object. To Create an Object of the Class you have to use the new Instance Method of the Class.

This is a bit advanced topic but here it is for only example sake. In practice it is very, very rarely used.