CPP Methods

What Is a Method?

  • Methods appear inside class bodies.
  • They contain local variable declarations.
  • Java statements that are executed when the method is invoked.
  • Methods may return a value which can be:
    1. a primitive type.
    2. a reference type
    3. or the type void, which indicates no returned value.
  • Methods may take arguments of same type as for return values – 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;
  }
}
What is Static Methods
  • Static methods (class methods), like static variables, belong to the class.
    (not the object of a class)
  • They can be invoked by name, through the class name, without any objects around.
  • Static methods can directly access only other static members of the class.
How to be define in a class:
...
 static String wheels() {           // static method
   return "I have 4 wheels!";
}
...
What is Variable-Length Argument Lists.
  • Java 5.0 introduced variable-length argument lists or "varargs" for methods.
  • syntax for declaring the varargs method uses ellipses (...) where the square brackets of an array might go.
Variable-Length Argument example:
...
void printObjects( Object ... list ) {
   // list is an Object [] (array)
   for( Object o : list )
       System.out.println( o );
}
...
What is Method Overloading.
  • Method overloading is the ability to define multiple methods with the same name in a class.
  • Overloaded methods to be executed are selected by the compiler at compiling time.
  • The Compiler picks the correct method based on the arguments passed to the method.
Method Overloading example:
...
class PrintStream {
        void print( Object arg ) { ... }
        void print( String arg ) { ... }
        void print( char [] arg ) { ... }
        ...
 }
...
What is Overriding Methods.
  • When you define a method that has exactly the same method signature as a method in its superclass.
  • A common programming error in Java is to accidentally overload a method when trying to override it.
  • The new annotations syntax in Java 5.0 provides a way to get the compiler to help with this problem.
    class Cat extends Mammal {
      @Override
      void sleep( ) { ... }
    }
         
  • Overridden methods, on the other hand, are selected dynamically at runtime.
  • You can't "override" a static method with an instance method.
    (static method in a super-class can be shadowed by another static method in a sub-class)
  • You can use the final modifier to declare that an instance method can't be overridden in a subclass.
  • For a method to qualify as an overridden method in a subclass, it must have exactly the same number and types of arguments.
  • As of Java 5.0, when you override a method, you may change the return type to a subtype of the original method's return type.
Method Override example:
...
  class Animal {
        Animal create( ) { ... }
    }
    class Mammal extends Animal {
        Mammal create( ) { ... }
    }
...
What is Casting.
  • A cast explicitly tells the compiler to change the apparent type of an object reference.
  • In Java, casts are checked both at compile time and at runtime to make sure they are legal.
  • Attempting to cast an object to an incompatible type at runtime results in a ClassCastException.
  • A cast can be used to narrow or downcast the type of a reference to make it more specific.
Casting example:
...
    Animal creature;
    Cat simon;               // Cat is sub-class of Animal
    // ...
    creature = simon;        // OK
    // simon = creature;     // Compile-time error, incompatible type
    simon = (Cat)creature;   // OK
...
  • You can check this with instanceof before you perform the cast:
...
    if ( creature instanceof Cat ) {
        Cat cat = (Cat)creature;
        cat.meow( );
    }
...
What about Constructors.
  • A constructor is a special method with the same name as its class and have no return type.
  • It's called when a new class instance is created.
  • Gives the class an opportunity to set up the object for initial use.
  • Can accept arguments and can be overloaded.
  • They are not inherited like other methods.
Constructor example:
...
class Date {
  long time;
  Date() {
    time = currentTime();
  }
  Date(String date) {
    time = parseDate(date);
  }
  ...
}
...
Overloaded Constructors.
  • A constructor can refer to another constructor in the same class using the this() operator.
  • The special call to this() must appear as the first statement in our delegating constructor.
Overloaded Constructor example:
...
class Car {

  String model;
  int doors;

  Car(String model, int doors) {
    this.model = model;
    this.doors = doors;
    // other, complicated setup
    ...
  }

  Car(String model) {
    this(model, 4 /* doors */);
  }
  ...
}
...
  • Making this() call to a contructors from other methods is illegal.
Superclass Constructors.
  • A constructor can refer to a superclass constructor using the super() operator.
  • The special call to super( ) must appear as the first statement in our delegating constructor.
Superclass Constructor example:
...
class Person {
  Person(String name) {
    //  setup based on name
    ...
  }
  ...
}
class Doctor extends Person {
  Doctor(String name, String specialty) {
    super(name);
    // setup based on specialty
    ...
  }
  ...
}
...
  • Making super() call to a superclass contructors from other methods is illegal.
How to use super & this operators.
  • You can refer to the members of the same class using this reference operator.
  • You can refer to the members of the superclass for the class using super reference operator.
Superclass Constructor example:
...
class Person {
  String name
  Person(String name) {
    this.name = name;
    ...
  }
  void Initiate () {
    ...
  }
}

class Doctor extends Person {

  Doctor(String name, String specialty) {
    super(name);
    super.Initiate();
  }
  ...
}
...
What about Constructors and Initialization.
  • How constructors are chained together and when instance variable initialization occurs can be devided in the following alternative cases:
    1. If the first statement of a constructor is an ordinary statement i.e., not a call to this( ) or super( ).
      • Java inserts an implicit call to super( ) to invoke the default constructor of the superclass.
      • Java initializes the instance variables of the current class.
      • Execute the statements of the current constructor.
    2. If the first statement of a constructor is a call to a superclass constructor via super( ).
      • Java invokes the selected superclass constructor.
      • Java initializes the instance variables of the current class.
      • Execute the statements of the current constructor.
    3. If the first statement of a constructor is a call to an overloaded constructor via this( ).
      • Java invokes the selected constructor.
      • Execute the statements of the current constructor (the initialization of instance variables has already occurred in the called constructor).

© 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.