This article introduces object-oriented polymorphism in the Java language.

Polymorphism is the ability to have many different manifestations or forms of the same behavior.

Such as:

Little Agi ao, he is an anchor, is also a person.

Little Agio is an object,

This object has both anchor and human form.

An object with multiple forms is called an object polymorphism.

Representation of polymorphism in code

How do I represent polymorphism in code?

A parent class reference refers to a subclass object.

Parent class name Object name =newSubclass name ();Copy the code

It doesn’t have to be a superclass reference, it can be:

Interface Name Object name =newImplementation class name ();Copy the code

Create a parent class:

public class A {
    public void method(a) {
        System.out.println("Superclass method"); }}Copy the code

Create a subclass that inherits and overrides the method method of the parent class:

public class B extends A {
    @Override
    public void method(a) {
        System.out.println("Subclass method"); }}Copy the code

To use polymorphic notation:

public class Main {
    public static void main(String[] args) {
        A a = newB(); a.method(); }}Copy the code

Output result:

The subclass methods

The output is the method of the subclass, if the parent class has a method that the subclass does not overwrite, then it will look up, that is, the subclass does not find the parent class.

We add a new method to the parent class:

public class A {
    public void method2(a) {
        System.out.println("Superclass-specific methods"); }}Copy the code

Subclasses do not override:

public class B extends A {
    // Write nothing
}
Copy the code

Call this method:

public class Main {
    public static void main(String[] args) {
        A a = newB(); a.method2(); }}Copy the code

Output result:

Superclass-specific methods

To summarize:

  • Access member variables directly by the object name, the left side of the equals sign whose method you use first, if not, look up

The use of member methods in polymorphism

There’s a saying: compile to the left, run to the right. (Here left refers to the left side of the equals sign, and right refers to the right side of the equals sign)

What does that mean? Code first:

Create a new parent class and write two methods: eat and giao. Note that giao is unique to the parent class.

public class Animal {
    public void eat(a) {
        System.out.println("Animals eat.");
    }

    public void giao(a) {
        System.out.println("Animals in Giao"); }}Copy the code

Create a new subclass that inherits the parent class and overrides the parent class’s eat method, then writes a specific method run:

public class Cat extends Animal {
    @Override
    public void eat(a) {
        System.out.println("The cat is eating the fish.");
    }

    public void run(a) {
        System.out.println("The cat is running"); }}Copy the code

Call each method:

public class Main {
    public static void main(String[] args) {
        Animal a = new Cat();
        a.eat();  // Output: the cat is eating fish
        a.giao(); // Output: animal in giao
        a.run();  // Error compiling}}Copy the code

Line by line:

  • Line 3, polymorphic, refers to a subclass object
  • Line 4: CalleatMethod, becauseeatMethods have parent and child classes, so subclasses are preferred, and output: cat is eating fish. Nothing wrong with
  • Line 5: CallgiaoMethod, this is a superclass-specific method, subclasses don’t have it, so look up and output: animal in GIao. There is nothing wrong with also
  • Line 6, callrunMethod, which is specific to subclasses, and the formula:Compile to the left. On the left is the superclass, there’s no superclassrunMethod, so compilation error (specific reason: object onceupcastingIs the parent class, so you can’t call things that are unique to subclasses, such asrunMethods)

If you want to use the run method, you have to create it in the parent class.

Member variables versus member methods

  • Member variables: Compile to the left, run to the left
  • Member methods: Compile to the left, run to the right

The benefits of polymorphism

Suppose we have three classes, all with work methods:

  • Employee class (Parent Class)

    work();  / / in the abstract
    Copy the code
  • Lecturer category (Sub-category)

    work();  / / lecture
    Copy the code
  • Teaching Assistant (Subclass)

    work();  / / coach
    Copy the code

If not polymorphic, use subclasses only:

Teacher t = new Teacher();
t.work();  // The teacher lectured
Assistant a = new Assistant();
a.work();  // Teaching assistant tutoring
Copy the code

The only thing we need to do is call the work method, regardless of whether you’re lecturing or tutoring.

To use polymorphic writing: compare the code above:

Employee t = new Teacher();
t.work();
Employee a = new Assistant();
t.work();
Copy the code

The benefit is clear: the method called to the left of the equals sign remains the same regardless of which subclass object is substituted for new on the right.

Of course, there are other benefits, which you’ll learn more about later.

The upward transformation of the object

The upward transformation of an object, as I’ve written above, is just polymorphic.

Format:

Parent class name Object name =newSubclass name (); Animal animal =new Cat();
Copy the code

Meaning:

Create a subclass object on the right and treat it as a parent class.

Created a cat and treated it like an animal.

Note: Upward transition must be safe. There is a drawback, however, that once an object is upcast into a parent class, it cannot call the content that is unique to subclasses (solution: downcast).

The downward transformation of an object

The downward transformation of an object is actually a reductive action.

Format:

Subclass name Object name = (subclass name) superclass object;Copy the code

Meaning:

Restore the parent object to its original object.

To put it simply, it was originally a cat, turned upward into an animal, and then turned downward back into a cat.

Animal animal = new Cat(); // Originally a cat, transformed upward into an animal
Cat cat = (Cat) animal; // The cat has been treated as an animal
Copy the code

Something like this:

int num = (int) 10.0; // true
int num = (int) 10.5; // false -> Loss of accuracy
Copy the code

Matters needing attention:

1. You must ensure that the object was originally created as a cat in order to descend to a cat

2. If the object was not a cat when it was created, and now you have to turn it down to a cat, do you think you are a sand sculpture? Error: ClassCastException

Use the instanceof keyword for type determination

One question: how do you know what subclass a parent refers to?

In short, how do you know if a reference to a superclass refers to a cat or a dog?

The answer: use the keyword instanceof.

Format:

The name of the objectinstanceofThe name of the subclassCopy the code

Returns a Boolean type:

public class Main {
    public static void main(String[] args) {
        Animal animal = new Cat();  // It was a cat
        animal.eat();  / / the cat eat the fish

        // If you want to use subclass-specific methods, you need to transition down
        if (animal instanceof Cat) { // true
            Cat cat = (Cat) animal;
            cat.run(); / / the cat is running}}}Copy the code

Note: When using downward transitions, be sure to use the instanceof keyword to avoid ClassCastException.