Generating the correct behavior in Java

Source: Internet
Author: User

Knowing that all the methods in Java are bound through late binding, you can write your own code to communicate with the underlying class. At this point, all the derived classes are guaranteed to work properly with the same code. Or alternatively, we can "send a message to an object and let the object decide what to do." ”

In object-oriented program design, there is a classic "shape" example. Because it is easy to visualize, it is often used to illustrate the problem. Unfortunately, it may mislead beginners into thinking that OOP is designed for graphical programming only, which is certainly wrong.

The shape example has a base class, named shape, and a large number of derived types: Circle (Round), Square (square), triangle (triangle), and so on. People like this example because it is easy to understand the concept of "a circle belongs to a type of shape". The following inheritance diagram shows us their relationship:

The trace form can be easily represented by the following statement:

Shape s = new Circle ();

Here, we create the Circle object and assign the result handle to a shape immediately. The surface appears to be an error operation (assigning one type to another), but is actually entirely feasible-because, according to the inheritance relationship, circle belongs to shape. Therefore, the compiler approves the above statement and does not prompt us with an error message.
When we call one of the base class methods (already overridden in a derived class):
S.draw ();
Similarly, you might think that you would call the shape's draw (), because this is a shape handle. So how does the compiler know what to do with everything else? But this is actually called Circle.draw (), because late binding is already involved (polymorphism).
The following example illustrates the problem from a slightly different point of view:

: Shapes.java//Polymorphism in Java class Shape {void Draw () {} void Erase () {}} class Circle extends Shape 
  {void Draw () {System.out.println ("Circle.draw ()"); 
  } void Erase () {System.out.println ("circle.erase ()"); 
  Class Square extends Shape {void Draw () {System.out.println ("Square.draw ()"); 
  } void Erase () {System.out.println ("square.erase ()"); 
  Class Triangle extends Shape {void Draw () {System.out.println ("Triangle.draw ()");
  } void Erase () {System.out.println ("triangle.erase ()");  The public class Shapes {public static Shape Randshape () {switch (int) (Math.random () * 3)) {default://To
      Quiet the compiler case 0:return new Circle ();
      Case 1:return New Square ();
    Case 2:return new triangle ();
    } public static void Main (string[] args) {shape[] s = new shape[9]; Fill up the array with shapes:for (int i = 0; i < s.length; i++) S[i] =Randshape ();
  Make polymorphic method calls:for (int i = 0; i < s.length i++) S[i].draw (); }
} ///:~

For everything derived from shape, shape creates a universal interface-that is, all shapes can be depicted and deleted. Derived classes override these definitions and provide unique behavior for each particular type of geometric shape.
In the main class shapes, a static method, named Randshape (), is included. Its role is to generate a handle for a randomly selected shape object each time it is invoked. Please note that the tracing style is in each return statement. This statement takes a handle to a circle,square or triangle and sends it as a return type shape to the method. So whenever this method is invoked, there is absolutely no chance of knowing what its specific type is, as it is sure to get a simple shape handle.
Main () contains an array of shape handles, where the data is filled in by calls to Randshape (). At this time, we know that we own shape, but we do not know any other specific situation (the compiler also does not know). However, when we step into this array and invoke draw () for each element, the correct behavior associated with each type will magically occur, as shown in the following sample output:

Circle.draw ()
Triangle.draw () Circle.draw () Circle.draw ()
circle.draw
() Square.draw () Triangle.draw ()
Square.draw ()
Square.draw ()

Of course, because geometric shapes are randomly selected each time, each run can have different results. The reason why we want to highlight the random selection of shapes is to impress upon everyone that the compiler does not need to obtain any special information in order to make the correct call at compile time. All calls to draw () are made through dynamic binding.

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.