Witscale Test Center

2.2 Objects > 2.2.2 Instantiating a Class and invoking its methods


2.2.2 Instantiating a Class and invoking its methods

You need to instantiate the Account class to create objects from it. Each object will have its own state and behavior that can be changed independently. For instance, you can create the account of John Q as:

 

Account accOfJohn = new Account(“John”, 100); // instantiate Account Account accOfMary = new Account(“Mary”, 250); // instantiate Account

 

We have also seen how to invoke a method in chapter 1. You can invoke the methods of these objects by calling them on the object references as:

 

System.out.println(“John’s balance ” + accOfJohn.getBalance()); // prints 100

System.out.println(“Mary’s balance ” + accOfMary.getBalance()); // prints 250

 

Note that the two objects referenced accOfJohn and accOfMary have different states. Therefore, even if you are invoking the same method, it is being invoked on two different objects and hence it produces different results.

 With the above example you have successfully used the Account class as a blueprint that creates two account objects. These objects have common behavior but have different states. So the rule of thumb is whenever you write a Java class, you would define the common behavior of objects in its methods and changing state in variables.