Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Overloading, Overriding, Runtime Types and Object Orientation - Overloading Methods

  • overloaded methods can have the same name but must have different parameter lists
  • parameter lists are considered different if the order of the arguments are different
  • a subclass method can overload a superclass method

Examples (based on BB pg 194-5)

  • the following code shows the method test(int i, long j) in a Super class, and method test(long j, int i) in a Sub class
Super class:
    test(int i, long j);
    
Sub class
    test(long j, int i);    
  • this code will compile fine if any variables passed to the methods are easily recognizable as either an int or a long
    Sub sb = new Sub();
    // second arg is defined as L(ong); no ambiguity
    sb.test(100, 3000L);    

Output:
    uses test(int i, long j) in Super class    
  • however, if the compiler cannot differentiate between a long and an int a compiler error will occur
    Sub sb = new Sub();
    // causes compile-error, 3000 can also be an int
    sb.test(100, 3000);    

Ouput:
    compile-error: reference to test() is ambiguous    
!!! Warning !!!
  • When analyzing code, watch for ambiguous references that can cause compile errors.

Overloading constructors

  • you can overload constructors within the same class
    class SuperCtor {
        SuperCtor(){}
        SuperCtor(int i) {} // compiles ok
    }
  • you can't overload them in subclasses as they must have the same name as the class (ie they would have to have the superclass name and would therefore not be constructors in the subclass)
    class SuperCtor {
        SuperCtor(){}
    }
    
    class SubCtor() {
        SuperCtor(){}  // compile-error
    }

Also see

Example Code

Encapsulation Polymorphism isA/hasA Overloading Overriding Field Variables
Initialization Top-level Classes Inner Classes Static Nested Classes Local Classes Anonymous Classes