Przeciążanie metod - method overloading

 

Można tworzyć wiele metod o tej samej nazwie, takim samym zwracanym typie, ale wielu różnych zestawach argumentów.

class MethodsWithDifferentArguments {
  int doSomething( int a, int b ) {
    return [...SOMETHING...];
  }
 
  int doSomething() {
    return [...SOMETHING...];
  }

  int doSomething( double a ) {
    return [...SOMETHING...];
  }
}

 

Nie można tworzyć metod o tej samej nazwie, takim samym zestawie argumentów, ale różnym zwracanym typie.

Czyli następująca sytuacja jest niedozwolona:

// ERROR! Ten kod się nie skompiluje.

class MethodsWithDifferentReturnType {
  int doSomething( int a, int b ) {
    return [...SOMETHING...];
  }
 
  double doSomething( int a, int b ) {
    return [...SOMETHING...];
  }
}

 

 

Patrz także: