10 Kasım 2015 Salı

Method Override & Method Overload

Java – Method Override

Superclass içerisinde tanımlanan bir method, extend edildiği subclass içerisinde tekrardan tanımlanması method override denir.

Vehicle superclassdır.

public class Vehicle {

      void run() {

            System.out.println("Vehicle is running");
      }
}

Bike subclasstır ve Vehicle classını extend eder sonra run() methodunu tekrardan tanımlar.

public class Bike extends Vehicle {

      @Override
      void run() {

            System.out.println("Bike is running");
      }
}


Java – Method Overload

Aynı class içerisinde farklı parametre sayısı ve farklı parametre tipleri method tanımlamaya method overload denir.
public class Overload {

      void foo(int a, int b) { 
            System.out.println(a + b);
      }

      void foo(String a, String b) { 
            System.out.println(a + " " + b);
      }

      void foo(int i, String s, double d) { 
            System.out.println(" ");
      }
}

Aşağıdaki gibi aynı sayıda ve tipte parametre girilirse hatalı olur.

public class Overload {

      void foo(int a, int b) { 
            System.out.println(a + b);
      }

      void foo(int x, int y) { 
            System.out.println(" ");
      }
}


Hiç yorum yok:

Yorum Gönder