Methods and Instances

First we are going to create a class with methods and instances first before calling the main class method. Take a look at the class with methods and instances below:

mthodsNInstances
Subclass where all the methods and Instances are declared.

Now let me explain the codes:

  1. private String colorName –> From the line we know that we set the variable to private. Why we set the variable to be private? We want the methods inside the class where the variable is declared to access the variable and prevent the other classes from using that variable. We call this declaration as instance variable with private access. If you want the other classes to use the variable you can set it to public.
  2. public void setcolor(String color) –> This line of code is for creating a method that doesn’t return anything but takes in an argument of a string variable. This method is where we assign the argument that was passed in to the private variable that we talked about earlier.
  3. public String getcolor() –> Since we  setcolor ,we need a getcolor to get the colorName by returning a String variable colorName which is an instances variable with private access.
  4. public void saying() –> this method will be used to output the result. In this method we can call other methods to like “getcolor()” to give the color name information.
    NOTE: We print the string by using the printf method format where we can format the string.

    1. %s – for string
    2. %f– for float
    3. %d – for decimal
    4. %n – for newline.

      The format are to be with the hard corded strings follow by a comma and the variable name or method as can be seen from the above snippet of codes.

The main class have the similar codes as the “Methods and Parameters” section but we need to use call 2 method instead of 1 as shown in the snippet below.

mthodsNInstancesMainCLass
Main class calling the setcolor and saying method.

Since the user input need to be stored in the colorName variable which is set to private on another class. The main class need to call the setColor() method from subClass and pass the input to the method. Then only the user input will get stored to the private variable.

After setting the color, the main class will call the saying method from another class to print the final output.

 

Leave a comment