Google
 

 

up previous next contents
Up: 2. Day 2: The Previous: 2.8 Classes and objects Next: 2.10 Extending Classes   Contents

Subsections

2.9 Methods and parameters

2.9.1 Methods

  • Methods in Java define the behavior of the class.
  • Methods are similar to procedures or subroutines in other languages.
  • The real benefits of object orientation come from hiding the implementation of a class behind its operations.
  • Methods access the internal implementation details of a class that are hidden from other objects.
  • Hiding data behind methods is so fundamental to object orientation it has a name - encapsulation.
  • Methods have zero or more parameters.
  • A method can have a return value.
  • A method's statements appear in a block of curly braces { and } that follow the method's signature.
        public void speak ()
        {
            System.out.println("Hey Barney ...");
        }
    

2.9.1.1 Invoking a Method

  • Provide an object reference and the method name, separated by a dot (.):
        fred.speak();
    
  • Parameters are passed to methods as a comma-separated list.
  • A method can return a single value as a result, such as an int:
        public int add (int a, int b)
        {
            return a+b;
        }
    
  • A method can return no result:
        public void setFirstName (String firstName)
        {
            this.firstName = firstName;
        }
    

2.9.1.2 The this Reference

  • Occasionally the receiving object needs to know its own reference.
        public void move (double x, double y)
        {
            this.x = x;
            this.y = y;
        }