Java study notes 7-Polymorphism

Source: Internet
Author: User


Polymorphism

Polymorphism is also known as dynamic binding of "dynamic binding", "late binding", or "Run-Time bingding" at runtime 』.
It means that the method to bind depends on the object type when the program is running. Polymorphism is the third basic feature of object-oriented programming languages following data abstraction and inheritance.

Binding: connects a method call to the method itself
Early binding: When binding occurs before running the program (it is the responsibility of the compiler or connector)
Post-binding (late binding): determines the method to bind Based on the object type when the program is running.

Encapsulation creates a new data type by combining characteristics with behavior.
Implementation hiding sets the details to private to separate interfaces from implementations.
"Polymorphism" is a logical separation from the "class" perspective.

 

Shape S = new circle (); // upcasting: Convert the circle object upcast to the shape type
S. Draw ();

  1. Upcast (upload) is to use the object reference as the reference of the base class. (Note: Java knows the object type internally)
    BecauseDerived class is a type of base classTherefore, the reference (shape S) of the base class can accept objects of the derived class (circle ).
  2. After upcast, the base class reference calls the base class's own method (late binding ),
    Unless this method is late-bound, that is, override (override) of the derived class, the corresponding method (polymorphism) will be selected based on the object type ).

    The above code is used as an example: S is a reference of the shape type, unless draw () is a dynamically bound method (the derived class circle overwrites this draw ()),
    S. Draw () will call the draw () of the cicle. Otherwise, the method of the base class shape will be called.

  3. Both private and final methods use early-binding, because they cannot be overwritten. (Note: The Private method is automatically final)

    We recommend that you do not use the private method of the base class to name the method of the derived class. This will lead to people mistakenly think that the override method will be used,
    In fact, private is automatically final and cannot be overwritten.

Override (overwrite) indicates to write a "same" method in the derived class. This method is re-written.
(Note: 1. "same" indicates the same name and the parameter list and return values are the same. 2. The method must be non-final and non-private (the private method is automatically final ))
Overload: A method with the same name except the "same" method (that is, override.

When you want to manipulate a group of classes through a public interface, you can use abstract classes. Through the dynamic binding mechanism, the derived class methods that conform to the method features will be called.
Abstract class {}
Abstract classes can be abstract or non-abstract. A derived class inherits an abstract class. It either implements all abstract methods or converts itself to abstract.

 

//: C07: polyconstructors. java // constructors and polymorphism // don't produce what you might expect CT. import COM. bruceeckel. simpletest. *; abstract class glyph {abstract void draw (); glyph () {system. out. println ("glyph () before draw ()"); Draw (); // If you create a new derived class object and call the dynamic binding method in the base class constructor, // It uses the derived class to overwrite the version. System. out. println ("glyph () after draw ()") ;}} class roundglyph extends glyph {private int radius = 1; roundglyph (int r) {radius = r; system. out. println ("roundglyph. roundglyph (), radius = "+ radius);} void draw () {system. out. println ("roundglyph. draw (), radius = "+ radius) ;}} public class polyconstructors {Private Static Test monitor = new test (); public static void main (string [] ARGs) {ne W roundglyph (5); monitor. CT (New String [] {"glyph () before draw ()", "roundglyph. draw (), radius = 0 "," glyph () after draw () "," roundglyph. roundglyph (), radius = 5 "});}}///:~

If you create a new derived class object and call the dynamic binding method in the base class constructor, it uses the overwritten version of the derived class.

The actual initialization process is as follows:
1. Before doing other work, the memory allocated to this object will be initialized to a binary zero first.
2. As mentioned earlier, call the constructor of the base class first. The overwritten draw () method will be called (yes, called before the roundglyph constructor is called ),
At this time, it finds that the radius value is still zero due to the influence of the first step.
3. Data members are initialized in the order they are declared.
4. Call the body of the constructor of the derived class.

A good constructor should: Set the object state (fields) with the minimum workload, and avoid calling methods as much as possible.
The only method that the constructor can safely call is the final/private method of the base class. They will not be overwritten, so they will not generate such unexpected behavior.

Once you understand polymorphism, you will feel that everything should be inherited, because polymorphism is too clever. However, this will increase the design burden.
In fact, if you think of using inheritance when you encounter "Creating a class with an existing class", things will become complex without any need.
It is better to consider merging first, especially when you do not know which class to inherit. Merging doesn't force you to make the design into a class system.
In addition, it is more flexible, because when using synthesis, You can dynamically select the member type (and their behavior), and use inheritance,
You must specify the exact object type during compilation. The following program demonstrates this point:

//: c07:Transmogrify.java// Dynamically changing the behavior of an object// via composition (the "State" design pattern).import com.bruceeckel.simpletest.*;abstract class Actor {  public abstract void act();}class HappyActor extends Actor {  public void act() {    System.out.println("HappyActor");  }}class SadActor extends Actor {  public void act() {    System.out.println("SadActor");  }}class Stage {  private Actor actor = new HappyActor();  public void change() { actor = new SadActor(); }  public void performPlay() { actor.act(); }}public class Transmogrify {  private static Test monitor = new Test();  public static void main(String[] args) {    Stage stage = new Stage();    stage.performPlay();    stage.change();    stage.performPlay();    monitor.expect(new String[] {      "HappyActor",      "SadActor"    });  }} ///:~

There is a general rule "using inheritance to indicate different behaviors, but using Member data to indicate different States ". The preceding routines reflect both. The two Derived classes are used to indicate the differences between the act () method,
Stage uses merging to indicate State changes. In this case, different States may lead to different behaviors.

Downcast: transfers the base class back to the specific type of the derived class, so that the reference can call the Extended Interface of the derived class.

Java type transfer must be checked! Therefore, although it seems that some common type conversions are made with a pair of parentheses, the system will check these conversions during running,
To ensure
It is indeed the type you want to convert. If not, you will get a classcastexception. This kind of runtime type check is called "runtime type
Run-Time type identification (rtti )".

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.