Ning2018 / JavaFundamentals

0 stars 0 forks source link

override&overwirte&overload #5

Open Ning2018 opened 6 years ago

Ning2018 commented 6 years ago

From multiple resources: override: Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class, with the same method name and parameters. Overloading occurs when two or more methods in one class have the same method name but different parameters. e.g. class Animal{ public void bark(){ System.out.println("Animal Sound"); } } class Dog extends Animal{ public void bark(){ System.out.println("woof"); } //override bark() of Animal class public void bark(int num){ for(int I=0; I<num; I++) System.out.println("woof"); } // overload bark() of Dog class public void move(){ System.out.println("Dog move"); } }

public class TestDog{ public static void main(String[] args){ Animal a = new Animal(); Animal b = new Dog(); a.bark(); // Animal Sound b.bark(); // Woof b.move(); // error , there is no move() method in Animal class } }

private, final, static, constructor can not be overridden, override can not have lower authorization, can not throw wider exception.

Ning2018 commented 6 years ago

From multiple resources: signature of method: method name, number and type of its parameters. The signature does not include the return type or the list of thrown exceptions, and you cannot overload methods based on these factors.

A final modifier for a parameter is not part of the method signature.

static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}

static void add(int a, int b){} // does not overload, error, ambiguity