Examples/problems with Java Methods

In Java, a class is made up of several methods, which manipulate instance variables. These variables are rather like global items - they keep their value as long as the object exists, and they are not local to methods. If we need to alter instance variables from outside a class, the writer of the class has to provide us with 'set' and 'get' methods. Also, each instance of a class has its own copy of any instance variables. Of course, methods may also create and use temporary local variables. Here is an example of a class, named DemoClass:

class DemoClass {
    private int x=0, y=0;   // instance vars
    private String person="";

    public void setPerson(String name) {
        person = name;
    }

    public int getX() {
        return x;
    }

    public void setX(int xVal) {
        x = xVal;
    }

}
Another class might use DemoClass by:
public class MethodDemo ......{

..... GUI setup omitted

 public void actionPerformed(ActionEvent event) {
        // create 2 instances of DemoClass, try out its methods
        // we display values that we fetch from the instance, to see if they are correct

        DemoClass d, d1;      // declare the name and type (i.e class)
        d = new DemoClass();  // create the instance in RAM
        d1= new DemoClass();
        int a;
        d.setX(33);
        // etc....
    }
}

This declares d, d1 to be of type DemoClass, and creates instances, with x and y set to 0, and person set to an empty string. NB d and d1 have their own private copy of the instance variables.

Here we will show lots of examples of possible method definitions and example invocations - they don't all do useful things, but you might gain an understanding, which will help you when faced with the task of writing a new method in a class.

When writing and calling (invoking) methods, remember that :

The following are based on our above class, and its instance d. The methods we code will be placed within DemoClass e.g. under the setX method. They will be invoked from outside DemoClass. If we call them within the class, we omit the '.' dot notation.

Example: A method to return the sum of x , y Code: public int sumXY(){ int sum; //local sum = x+y; return sum; } // or simply: public int sumXY() { return x+y; } Invocation/call: int s; s = d.sumXY(); d.sumXY(); //Wrong! the returned result is not being used!
Example: A method to return the value of person Code: Public String getPerson() { return person; } Invocation: String p; p= d.getPerson();
Example: A method to add 10 to x Code: public void add(){ x = x+10; } Invocation: d.add(); d.add(10); //Wrong! the method has NO parameters
Example: A method to add any amount to x: Code: public void increase(int amount) { x= x+amount; } Invocation: d.increase(22); s=d.increase(22); //Wrong! - there is no result to make use of
Example: A method to increase x, but not if it goes above 1000: Code: public void increaseLimited(int amount) { if(x+amount <= 1000) x = x+amount; } Invocation: d.increaseLimited(33);
Example: A method to return the bigger of x, y Code: public int getBigger() { if (x>y) return x; else return y; } Invocation: int b; b = d.getBigger();
Example: A method to set the value of person, but not if the new value only has 1 or less characters: Code: public void setPerson(String s){ if (s.length() > 1) person = s; } Invocation: d.setPerson("john"); d.setPerson("w"); // person unchanged.
Example: A method to return a boolean value if either x or y is above 100: Code: public boolean outOfRange(){ if((x>100) || (y>100)) return true else return false; } Invocation: boolean b; b = d.outOfRange(); // or perhaps... if( d.outOfRange() ) ..display an error...
Example: To pass a textfield for x to be displayed in: Code: public void displayX(JTextField tf) { tf.setText( "x is " + x ); } Invocation: ....assume that textField2 has been set up as a JTextField d.displayX(textField2);

Now you have a go.
Put a new instance variable - an int named age - in DemoClass.

Write methods to do the following, and run the code. Check that any results are correct.

  1. two methods - to set and get age
  2. increment age by 1
  3. decrement age by 1, unless it would go below 0.
  4. a method named 'old' which returns true if age is above 30
  5. a method which adds its int parameter to age.
    You might invoke it by: d.addToAge(6);
  6. a method to return the smaller of age and x
  7. a method named toString. Most of the library classes have this. It should return a textual representation of the values of an object's intance variables. You can decide on the layout. For example, in our DemoClass, if the values of x is 10 and person is "John" then:
    
    s = d.toString()
    
    could return the string
    
    x
    10
    person
    John
    

  8. Mike Parr: m.parr@shu.ac.uk