The manifestation of polymorphism
1. Overloading and rewriting of methods
2, the polymorphism of the object
The polymorphism of the object
Upward transformation
The program will automatically complete
Parent class Parent Class object = Child class instance
Down transformation
Forced type conversion ( downward transformation must first be shifted upward, then downward )
Subclass sub-Class object = (subclass) Parent class instance
Eg:a a=new b;b b= (B) A;
The use of polymorphism
A simple example:
classA { Public voidTell () {}}classBextendsA { Public voidtellb () {}}classCextendsA { Public voidTELLC () {}} Public classDemo { Public Static voidMain (String args[]) {Say (NewB ()); Say (NewC ()); } Public voidsay (a a) {A.tell (); }}
Note: If you do not use polymorphism, you need to overload the say method, and there are several object calls that need to be overloaded several times. In this case, the more redundant code is generated. The demo code is as follows:
Public class demo{
Public Static void Main (String args[]) {Say (new B ()); Say (new C ()); } publicvoid say (b b) {B.tell (); } publicvoid say (c c) {C.tell (); }}
instanceof Keywords
Role
Determines whether an instance is an object of a class and returns a Boolean
The sample code is as follows:
Newinstanceofinstanceof newinstanceof instanceof B); execution Result: True false True True
Java Object-oriented---polymorphism