In Java there are a lot of inheritance, inherited variables, methods. in some subclasses to implement the method, the method name, pass the parameter, the return value is the same as the method in the parent class, but the implementation is not the same as the parent class, we need to rewrite the parent class method , for example, we have a class called animals, There is one called call in the animals class, and then we inherit the animals and the cat class and the dog, and cat and dog have their own special calls, the program is as follows:
1 classAnimals {2 Public voidCall () {3SYSTEM.OUT.PRINTLN ("Ah ah ah ah ah ah!"));4 }5 }6 7 8 Public classCatextendsAnimals {9 @OverrideTen Public voidCall () { One ASystem.out.println ("Meow meow meow meow Meow"); - } - } the - - Public classDogextendsAnimals { - + @Override - Public voidCall () { +System.out.println ("Barking and Barking")); A } at - Public Static voidMain (string[] args) { -Animals Animals =NewAnimals (); - Animals.call (); - -Cat cat =NewCat (); in Cat.call (); - toDog dog =NewDog (); + Dog.call (); - } the *}
The printing results are as follows:
Overloading is implemented in a class with multiple methods with the same name, but with different parameters, including parameter types, number of arguments, and no parameters, in short, the parameters of each overloaded method must be different.
Now I'm going to write a small program that compares two numeric values to the following code blocks:
1 Public classCompare {2 3 Public voidMaxintAintb) {4System.out.println (a>b?a:b);5 }6 7 Public voidMaxfloatAfloatb) {8System.out.println (a>b?a:b);9 }Ten One A Public voidMax () { - /** - * No parameter overload the * */ -System.out.println ("Coding ..."); - } - Public Static voidMain (string[] args) { + //TODO auto-generated Method Stub -Compare Compare =NewCompare (); +Compare.max (102, 23); ACompare.max (2.0f, 3.0f); at Compare.max (); - } - -}
Printing results such as:
Overrides are shell invariant, core variable. That is, the method name does not change, the parameter is unchanged, the concrete implementation can be changed. You typically declare a method in a parent class and override it in a subclass.
Overloading is the method name unchanged, but the parameters must be changed. And overloaded methods are generally written in a class. Use a graph to indicate the following differences:
Overrides and overloads in Java