We’ve looked at building our Java Class (here and here), but how do we use it? Let’s look into this.
Once our class is complete, or complete enough – we can always go in and modify it further based upon new functionality needed, fixes to bugs, etc, we can instantiate it. That is, we can create an object based off of our class.
To do so is similar to create a new object that comes with Java, and similar to creating a primitive variable. We will define the object Class type, the object’s instance name, and call the constructor as in the example below.
Note: we are assuming that you are in another class, with a static void main() method or similar instance for where this is being called. However, you can create objects inside any method or class that you want. They can last for the whole project, or for a short period of time, it’s up to you.
Greeting welcome = new Greeting();
This will create the object with the default constructor. If we want to create it with a different constructor, we need to pass in parameters to the constructor so that it is changed.
Greeting welcome2 = new Greeting("Hello World.");
System.out.println(welcome2.toString());
Here we use a different constructor, and then call a method of that object. To call a method, we use the dot (.) operator to specify the object, then the method for that specific object.
As long as we have permission to call the object, and the method, we can make this reference. We can call any of the methods using this manner, as long as we receive the return data and pass appropriate objects as is needed.
Intro to Java Classes – Instantiate a Object was originally found on Access 2 Learn