Next introduces Java's third-largest feature-polymorphism
/* polymorphic: The same object (thing), at different times manifested in different states. For example: cats are cats and cats are animals. Water (liquid, solid, gaseous). The precondition of polymorphism: A: To have an inheritance relationship. B: There are methods to rewrite. Not really, but it doesn't make sense without it. Animal d = new Cat ();d. Show (); Animal d = new Dog ();d. Show (); C: To have a parent class reference to the child class object. The parent F = new Child (); Show polymorphism in code. Member Access features in polymorphic: A: Member variable compile look to the left, run look left. B: When constructing a subclass object, the constructor method of the parent class is accessed to initialize the data of the parent class. C: Member method compile look left, run see (right). D: Static method Compile look left, run look left. Static and class-related, not a rewrite, so, access is still to the left, however, because the member method exists method overrides, so it runs look to the right. */class FU {public int num = 100;public void Show () {System.out.println ("show Fu");} public static void function () {System.out.println ("function Fu");}} Class Zi extends Fu {public int num = 1000;public int num2 = 200;public void Show () {//method override for parent class System.out.println ("Show Zi ");} public void Method () {//own methods System.out.println ("Zi");} The public static void function () {///static method also needs to be "rewritten", not really a rewrite System.out.println ("function Zi");}} Class Duotaidemo {public static void main (string[] args) {//To have a parent class reference to the child class object. Parent F = new Child (); Fu f = new Zi (); System.out.println (f.num);//cannot find the symbol, there is no num2//system.out.println (F.NUM2) in the parent class, f.show ();//cannot find the symbol, there is no method in the parent class ()// F.method (); F.function ();}}
The execution result is: 100
Show Zi
function Fu
Disadvantages of polymorphism:
/* polymorphic Disadvantages: You cannot use the unique features of subclasses. */class Fu {public void Show () {System.out.println ("show Fu");}} Class Zi extends Fu {public void Show () {System.out.println ("show Zi");} public void Method () {System.out.println ("method Zi");}} Class DuoTaiDemo3 {public static void main (string[] args) {//Test fu F = new Zi (); F.show (); F.method ();//Because there is no method () in the parent class. So the error. Error description: Cannot find Symbol}} So how should we solve this problem? Downward transformation. An introduction to the downward transformation will be made in the next article.
Object-oriented (play polymorphism) for the first season of getting Started with Java