Constructors

In the earlier post of Methods and Parameters, we talked about how constructors works for default constructor. Now in this post we are also going to talk about constructor but is a parameter-ised  constructor. Parameter-ised constructor are a constructor with parameter. Therefore, constructor must have the same name as the class, do not have a return type and must pass in a parameter as soon as an the object is created in order for that method to be executed.

The snippets of code below are similar to Methods and Instances snippets but we coded the constructor out with an argument.

First, the class with methods that the main class will use:

constructorSubClass
Class with constructors and other methods

Next, the main class where it will call the other class’s methods:

constructorMainClass.JPG
Main Class where the object was created & pass in the value as an argument.

Since the object pass in an argument, we need to create a constructor that take in the given value from the main class to its class and process the method. Then the class object calls the class method ‘saying()’ where the saying method will give the final output after the execution of ‘getcolor()’ method gets the instance variable value.

Note: We can create multiple class object of the same class but rename the object differently with different variable as its parameter to access the multiple object.

Leave a comment