Java Method generally

Java Methods generally

  • All methods will always be defined within the body of a class.
  • They can contain local variable declarations.
  • They will contain java statements that are executed when the method is invoked.
  • Methods may return one value which can be one of:
    1. a primitive type (double, int, float, char etc.).
    2. a reference type (to an object of a class or an array of objects)
    3. or the type void, which indicates that no value will be returned.
  • Methods can take arguments of same type as the return types – except void.
    Example class file: Bird.java:
    
    class Bird {
    
      int xPos;
    
      double fly(int x, int y) {
        // distance is a local variable for the method
        double distance = Math.sqrt(x * x + y * y);
        // the local variable,xPos, shadows or hides 
        // the name of the instance variable 
        int xPos = x;
        // You can use the special reference this operator 
        // any time you need to refer explicitly to the current object 
        this.xPos = y;
        return distance;
      }
    }
    
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.