Java Learning notes 7--polymorphism

Source: Internet
Author: User
Tags abstract bind constructor final inheritance interface reference
Notes polymorphism
Polymorphism (polymorphism) is also referred to as dynamic binding "dynamics binding", late binding after binding, or runtime binding "Run-time bingding".
It means to decide which method to bind, depending on the type of object, when the program is running. Polymorphism is the third basic feature of Object-oriented programming languages after data abstraction and inheritance.

Binding (binding): Connecting a method's call to the method itself
Pre-binding (early binding): When binding occurs before the program is run (that is, the compiler or connector is responsible)
Post-binding (late binding): Determines which method to bind, depending on the type of object, when the program is running.

Encapsulation (encapsulation) creates a new data type by combining the characteristics of the data (characteristics) with the behavior (behavior).
The "Hide implementation" (implementation hiding) completes the separation of the interface from the implementation by setting the details private.
Polymorphism is a way of dealing with this kind of logical separation by standing in the "class" angle.


--------------------------------------------------------------------------------



Shape s = new Circle (); Upcasting: Upcast The Circle object to the shape type
S.draw ();

Upcast (upload) is to use the reference of objects as a base class of reference. (Note: Inside Java, you know what type of object it belongs to)
Because the derived class is a type of base class, reference (Shape s) of the base class can accept objects of derived classes (circle)

After Upcast, the base class reference calls all of its own method (late binding),
Unless the method is Late-bound, the derived class is overridden (override) This method, the corresponding method (polymorphism) is selected according to the object type.

Take the preceding code as an example: s is a shape-type reference unless draw () is a dynamically bound method (the derived class circle the draw ()),
S.draw () will call Cicle's draw (), otherwise the call is base class shape own method

Both private and final methods adopt early-binding, because they cannot be override. (Note: The private method automatically is final)

It is recommended that you do not name the method of a derived class with the names of the private method of the base class. Because it makes people mistakenly think that they will override this method,
In fact, private automatically is final, can not be override.


--------------------------------------------------------------------------------

Override (overwrite) means that a "same" method is written in a derived class. Just rewrite the method.
(Note: 1. " Same "means: with the same name and parameter list and return value. 2.method must be non final, private (the private method automatically is final))
Overload: Method with the same name other than the "Same" method (that is, override).


--------------------------------------------------------------------------------


When you want to manipulate a group of classes through a common interface, you can use an abstract class. Through dynamic binding mechanisms, the derived class methods that conform to the method characteristics are invoked.
Abstract class {}
Abstract classes can be made either abstract or non abstract. A derived class inherits an abstract class, which either implements all of the abstract's method or turns himself into abstract.


--------------------------------------------------------------------------------



: C07:PolyConstructors.java
Constructors and polymorphism
Don ' t produce what you might expect.
Import com.bruceeckel.simpletest.*;
Abstract class Glyph {
abstract void Draw ();
Glyph () {
System.out.println ("Glyph () before Draw ()");
Draw ()//If you new a derived class object and invoke a dynamically bound method inside the base class constructor,
Then it will use that 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) {
New Roundglyph (5);
Monitor.expect (new string[] {
"Glyph () before Draw ()",
"Roundglyph.draw (), radius = 0",
"Glyph () after draw ()",
"Roundglyph.roundglyph (), radius = 5"
});
}
} ///:~
If you new a derived class object and invoke a dynamically bound method within the base class constructor, it will use that derived class to overwrite the version.

The real initialization process is this:
1. Before doing other work, the memory allocated to this object is first initialized to the binary 0.
2. As has been said previously, the constructor of the base class is called first. The overridden Draw () method (yes, called before calling the Roundglyph constructor) is invoked.
At this point, it found that the radius value was zero because of the first step.
3. Data members are initialized in the order in which they are declared.
4. Invokes the body of the constructor of the derived class.


A good constructor should: set the state of the object (fields) with minimal effort, and avoid calling the method as much as possible.
The only method that the constructor can call safely is the Final/private method of the base class. They are not overwritten and therefore do not produce such unexpected behavior.


--------------------------------------------------------------------------------

Once you understand polymorphism, you feel that everything should be inherited, because polymorphism is so clever. But doing so will add to the burden of design.
In fact, if you encounter the idea of using an existing class to create a new class, then it becomes unnecessarily complicated.
A better idea is to think about compositing first, especially if you don't know which class to inherit. Synthesis does not compel you to make the design into a class system.
It's also more flexible, because when you use compositing, you can dynamically select the type of members (and their behavior), and use inheritance,
You must specify the exact type of the object at compile time. This is illustrated by the following procedure:

: C07:Transmogrify.java
Dynamically changing the behavior of an object
Via composition (the "state").
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 guideline, "Use inheritance to represent differences in behavior, and use member data to represent differences in state". The above routines also embody both; two derived classes are used to represent the difference between the Act () method.
Stage, however, uses compositing to represent changes in state. In this case, the difference in state can cause the behavior to be different.


--------------------------------------------------------------------------------

Downcast: Returns the base class back to the specific derived class type so that reference can invoke the extended interface of the derived class

Java type passes are checked! So, although it looks like you've just made some normal type conversions with a pair of parentheses, when you run, the system checks for these transformations,
To make sure it's really the type you want to convert. If not, you will get a classcastexception. This run-time type check is called the "Run-time type
Authentication (run-time type identification abbreviated to RTTI) ".





Related Article

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.