1. Function overload (overloding)
concept: a function with the same name has a different argument list.
function: to achieve the internal polymorphism of a single class, is static polymorphism.
Note the point:
(1) There is at least one difference in the type, number and order of the parameters.
(2) cannot overload by access permission , return type , thrown exception .
2. Function rewrite (overrideing)
Concept: defining a method in a subclass with the same name and parameters as its parent class, or when the parent class reference of a subclass object uses this method, invokes the definition in the subclass.
function: to achieve polymorphism in inheritance is the manifestation of polymorphism between parent class and subclass.
Note the point:
(1) The method name, parameter, and return value must be the same.
(2) The subclass method cannot narrow the access rights of the parent class method.
(3) A subclass method cannot throw more exceptions than the parent class (subclasses can not throw exceptions).
(4) A method that is defined as final cannot be rewritten.
3 . the principle of whether an object reference can invoke a method
(1) Upward transformation: The subclass is transformed into the parent type.
(2) Subclass object reference: A method can be invoked if it exists in a subclass definition, otherwise it cannot be invoked.
(3) Parent class object reference: The method exists in the parent class definition can be invoked, the invocation result is based on the polymorphism principle, otherwise it cannot be invoked.
|
Animal class
Public class Animal {
Public void introduce () {
System.out.println ("I am an animal!");
}
}
Cat class
Public class Cat extends Animal {
Rewrite the introduce of the parent class to implement the overriding
Public void introduce () {
System.out.println ("I am a cat!");
}
Realized the overloading
Public void Introduce (String name) {
System.out.println ("I am a cat, my name is:" + name);
}
}
Dog class
Public class Dog extends Animal {
Rewrite the introduce of the parent class to implement the overriding
Public void introduce () {
System.out.println ("I am a dog!");
}
Realized the overloading
Public void Introduce (String name) {
System.out.println ("I am a dog, my name is:" + name);
}
}
Test class
Public class Test {
Public Static void Main (string[] args) {
Overriding is a manifestation of polymorphism between the parent class and the subclass
Animal animal1 = new Animal ();
Animal Animal2 = new Cat ();
Animal Animal3 = new Dog ();
Animal1.introduce ();
Animal2.introduce ();
Animal3.introduce ();
Animal2.introduce ("JACK"); It's the wrong use.
Animal3.introduce ("JACK"); It's the wrong use.
Overloading is the embodiment of polymorphism in a class
Cat cat = new cat ();
Cat.introduce ();
Cat.introduce ("JACK");
}
}
The results of the operation are as follows:
I am an animal!
I am a cat!
I am a dog!
I am a cat!
I am a cat, my name Is:jack
|