Thinking in Java Note 8 Polymorphism

Source: Internet
Author: User
Tags export class
  • Polymorphism
Polymorphism separates interfaces and implementations from each other by separating what is done and how to do it. It not only improves the code structure and readability, but also creates scalable programs. Encapsulate the creation of data types by combining features and behaviors, and 'implement invisibility 'separates the interfaces and implementations by privatize the details. Polymorphism is used to eliminate coupling between types. Polymorphism allows different subclasses of the same base class to show business trip based on the behavior of the method (implemented by overwriting the parent class through the subclass), and these methods are called in the same way. Application polymorphism, the Code modifications we make will not damage other aspects of the programmer that should not be affected. It helps us to separate the changed things from the unchanged things.
  • Further on upward Transformation
The practice of referencing an object as a reference to its base type is called upward Transformation (in the inheritance tree painting method, the base class is placed above ). If each subclass contains an overload of the same method in the base class, you can call its base class method during the call, bind the method at runtime, and call the subclass method.
  • Method call binding
Associating a method call with a method subject is called binding. If it is bound before the program is executed (implemented by the compiler and the Connection Program), it is called the pre-binding (such as the C language ). Binding Based on the object type at runtime is called dynamic (runtime) binding (Java ). In addition to static and final methods (including private methods), Java is dynamically bound.
  • Polymorphism Defects
Only non-private methods can be overwritten. In the export class, it is best to use a method name different from the private method in the base class. Domain and static methods do not have polymorphism. When the sub object is transformed to a super reference, any domain access operations will be parsed by the compiler, so it is not a polymorphism. Static methods are associated with classes rather than objects, and therefore do not have polymorphism.
  • Constructor and Polymorphism
The constructor of the base class is always called during the construction process of the exported class. the constructor's task is to check whether the object is correctly constructed, the elements in the base class can be initialized only in the base class constructor, and the complete object can be constructed only by calling in order.
  • Inheritance and cleanup
The order of destruction should be the opposite of the initialization order, and the field should be the opposite of the declared order. For the base class, you should first clear the export class and then the base class. If the member object has an object sharing problem, it cannot be cleared directly. In this case, you must count the reference in the class of the shared object. When the number of references is 0, the member object must be cleared.
  • The behavior of polymorphism Methods inside the constructor

class Glyph {
void draw() { print ( "Glyph.draw()" ); }
Glyph () {
print (
draw();
print (
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
RoundGlyph( int r) {
radius = r;
print ( "RoundGlyph.RoundGlyph(), radius = " + radius );
}
void draw() {
print ( "RoundGlyph.draw(), radius = " + radius );
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
} /* Output:
Glyph () before draw()
RoundGlyph.draw(), radius = 0
Glyph () after draw()
RoundGlyph.RoundGlyph(), radius = 5
*///:~

When draw () is called in the glyph () constructor, the draw () method of roundglyph is called. At this time, the radius has not been initialized. Therefore, the constructor has an effective principle: Only initialize values, and try to avoid calling other methods.
  • Covariant return type
You can return an export type of the return type of the base class method in the override method of the export class.     

class Grain {
public String toString() { return "Grain" ; }
}
class Wheat extends Grain {
public String toString() { return "Wheat" ; }
}
class Mill {
Grain process() { return new Grain(); }
}
class WheatMill extends Mill {
Wheat process() { return new Wheat(); }
}


  • Design with inheritance-state mode
A general principle is to inherit the differences between behavior and use fields to express changes in status. In this example, two different classes are inherited to express the differences between Act (). Stage uses combinations to change its state. In this case, this kind of status change also produces behavior changes.

import static rasa.util.Print.*;

class Actor {
public void act() {}
}

class HappyActor extends Actor {
public void act() { print ( "HappyActor" ); }
}

class SadActor extends Actor {
public void act() { print ( "SadActor" ); }
}

class Stage {
private Actor actor = new HappyActor();
public void change() { actor = new SadActor(); }
public void performPlay() { actor .act(); }
}

public class Transmogrify {
public static void main(String[] args) {
Stage stage = new Stage();
stage.performPlay();
stage.change();
stage.performPlay();
}
} /* Output:
HappyActor
SadActor
*///:~

  • Design with inheritance-pure inheritance and Expansion
Pure inheritance: The export class and the base class have the same method (is-a relationship ). The export class can completely replace the base class. When using the class, you do not need to know any additional information about the subclass. You only need to transform from an export class to an upstream class, and never need to know the exact type of the object being processed. Extension: The export class is like a base class, which has the same basic interface but has other features implemented by additional methods. The extension part of the export class interface cannot be accessed by the base class. Therefore, you need to find out the exact type of the object so that you can access the extension method of this type. The upward transformation will be a specific type of information. The downward transformation can obtain the type information, but the correctness of the downward transformation must be ensured. During the runtime, the transformation will be checked to ensure that it is the type we want (runtime type identification rtti). If the transformation is incorrect, classcastexception will be reported.

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.