Java .

Java Methods

constructor, accessor, and mutator methods


constructor methods
Special method for creating new instance of a class. Must have the same name as the class it constructs. Below (line 4) is the constructor for Cat.


accessor methods
Methods that return variables. The accessor method name should start with "get". Below (line 8) is the accessor named getCatsColor.


mutator methods
Methods that alter variables. The mutator method name should start with "set". Below (line 12) is the accessor named setCatsColor.
1 class Cat {
2     private static String animalType = "feline";
3     private String catColor;
4     Cat(String colorIn)
5     {
6         setCatsColor(colorIn);    
7     }
8     public String getCatsColor()
9     {
10        return this.catColor;  
11    }
12    public String setCatsColor()
13    {
14        this.catColor;  
15    }
16    
17    public static void main (String[] argsIn) {
18        Cat patches = new Cat("calico");
19    }
20 }     

signature or method signature

What variable types and in what order they are passed to a method. The return type is not a part of the signature. In the folowing method "String, double" is the signature:
public int returnAnInt(String stringIn, double doubleIn) {
    int intToReturn = 1;
    if (stringIn.equals(String.valueOf(doubleIn))
        {
            intToReturn = 2;
        }
        
    return intToReturn;
}

overloaded method

Two or more methods with same name, different signature, return types can vary - but do not have to.
public int returnOneNoMatterWhat(String stringIn, double doubleIn) {
    int intToReturn = 1;
    return intToReturn;
}         

public int returnOneNoMatterWhat(int intIn) { int intToReturn = 1; return intToReturn; }
Comments Comments are left by visitors to FluffyCat.com and may or may not be accurate.
Comment by Anonymous on 2011-12-11 Rate this Comment

Be the first to comment on Java Methods.
Nice tutorial. If you are still maintaining this page, please change:

mutator methods
Methods that alter variables. The mutator method name should start with "set". Below (line 12) is the accessor named setCatsColor.

to

mutator methods
Methods that alter variables. The mutator method name should start with "set". Below (line 12) is the mutator named setCatsColor.

Comment by TheMadProfessor on 2013-05-22 Rate this Comment

It appears to me that there is a problem with one of your mutator methods: setCatsColor does not seem to do anything and the method signature does not match its usage in the constructor. I believe what you intended was this

12 public void setCatsColor(String newColor)
13 {
14 this.catColor = newColor;
15 }

 
Sign in to comment on Java Methods.