Thinking in Java---multi-state research

Source: Internet
Author: User
Tags export class types of functions

Inheritance, encapsulation, polymorphism are the three main features of object-oriented programming. In fact, in a way, inheritance and encapsulation are in preparation for polymorphism, and here we understand the important concept of polymorphism and its implementation principle.
I. What is polymorphic
The so-called polymorphism means that objects of different classes are allowed to respond to the same message. That is, the same message can be used in a variety of different ways depending on the sending object. (Sending a message is a function call).
We know that Java supports upward transformation, so for subclasses that inherit from the same base class, we can treat the object as a base class object. Therefore, polymorphism refers to some methods of calling base classes, which show different characteristics depending on the object of the subclass being passed in. (similar to the fact that we are under different software, pressing the same shortcut key will have different reactions). The following code demonstrates polymorphism: Bicycle Tricycle Unicycle are subclasses of the cycle class, and then all four classes have wheels methods to return the number of their wheels. The wheels method in the Ridetest class sees all incoming objects as a cycle object, but when we pass the Bicycle,tricycle,unicycle object to it we can get the correct result, which is polymorphism.

 PackageLKL; Public  class Cycle {        Public int Wheels(){return 0; }} Public  class tricycleextendsCycle{              Public int Wheels(){return 3; }} Public  class BiCycle extends Cycle{      Public int Wheels(){return 2; }} Public  class unicycle extends Cycle{        Public int Wheels(){return 1; }} Public  class ridetest {          Public int Wheels(Cycle Cy) {returnCy.wheels (); } Public Static void Main(string[] args) {Ridetest RT =NewRidetest ();/// depending on the different sub-classes that are passed in, the behavior is called polymorphicSystem.out.println (Rt.wheels (NewUnicycle ())); System.out.println (Rt.wheels (NewBiCycle ())); System.out.println (Rt.wheels (NewTricycle ()));

Two. Multi-State implementation principle
The polymorphic implementation relies on two principles: 1. Upward transformation, 2. Late binding.
The upward transformation provided by Java allows us to treat the object of the subclass as a base class object, which is necessary for polymorphism because polymorphism requires that we treat all subclass objects as base class objects. The rationality of upward transformation is that all base classes have interfaces, and subclasses are bound to have them. This transformation does not occur when the calling subclass does not have an interface error.
We know that for a typical instance method, there should be an object that invokes it, so the compiler will associate a method invocation with an entity (the object). If you bind before the program executes, it is called a pre-binding. But for polymorphism, We only know at runtime how the object is called, so it doesn't work. Java introduces late binding (also called dynamic binding), which allows us to bind to the object's type when the program is run (which requires the ability to determine the type of the object at run time). This is also the core of the implementation of polymorphism. In C + + we use the virtual keyword to show that a function can be overridden by its subclasses, and that there is polymorphism. Corresponding to Java, except for the private static decorated function, the rest of the functions are late bound, that is, there is the possibility of polymorphism.

Three. Traps
First of all, not all functions are polymorphic, as the above-described function with private or static modifier is not polymorphic, because the precondition of polymorphism is inheritance and rewriting, the base class interface needs to be visible to the child class. Private decorated functions cannot be called by subclasses The static function is owned by the class and can be viewed as a function that cannot be inherited. Therefore, these two types of functions are not polymorphic. If we look at the concept of polymorphism, it seems that the member variables of the base class that are non-private are also polymorphic, but not actually, This is the Java rule. The following code shows these three scenarios:

Package LKL; Public classbasetest { Public intI=1; Public int getfiled(){returnI }Private void privatetest() {System. out. println ("Basetest.privatetest ()"); }///  static function       Public Static void statictest() {System. out. println ("Basetest.statictest ()"); }}package LKL; Public classTest1 extends basetest{ Public intI=9; Public int getfiled(){returnI }  ///Try overriding the base class's Privatetest ()     Private void privatetest() {System. out. println ("Test1.privatetest ()"); }  ///Try overriding the base class's Statictest ()     ///  @Override add override error stating that cannot be overridden       Public Static void statictest() {System. out. println ("Test1.statictest"); } Public Static void Main(string[] args) {Basetest BT =NewTest1 ();///   domain does not exist polymorphicSystem. out. println (BT.I); System. out. println (Bt.getfiled ()); BT.F ();///  statictest calls do not produce polymorphismBt.statictest (); }}

Four. An exercise
Create a base class that contains two methods. In the first method, you can call the second method, and then produce an export class that inherits from the base class, overwriting the second method in the base class. Create an object for the export class, transform it up to the base class type, and call the first method to explain what happened.

 Public  class Test1 extends basetest{        @Override/// rewrite second method         Public void Second(){//super.g ();System.out.println ("Test1.second ()"); } Public Static void Main(string[] args) {Basetest BT =NewTest1 ();        Bt.first (); }} Public  class basetest {        Public void  First() {System.out.println ("Base.first ()");       Second (); } Public void Second() {System.out.println ("Base.second ()"); }}

The result is:
Base.first ()
Test1.second ()

The reason for this is that we call first the object of this method is a subclass object, but because the first method is not overridden by the quilt class, it does not show polymorphism;
The object that we call the second function in first is also a subclass object, because the second function is overridden in subclasses, so it shows polymorphism.
This topic shows that rewriting is also a necessary condition for polymorphism.

Thinking in Java---multi-state research

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.