Understanding of downward transformation

Posted by cmgmyr on Sat, 15 Jan 2022 18:46:13 +0100

What is polymorphism? (understanding of the meaning of downward transformation)

Professional perspective: multiple objects of the same kind have different reactions and effects when receiving the same message;

From the perspective of code form: the object variable of the parent class calls the method overridden in the subclass (Note: there is often a parent class, but it has multiple subclasses, and one method of the parent class is overridden in these subclasses at the same time);

give an example:

  • Wine a = Jiannanchun

  • Wine b = Niulanshan

  • Wine c = Maotai flavor technology

    • In the above example, "wine" is the parent class, and the specific wine brands are children of the "wine" category. We can reference different subclasses only through the parent class of wine, which is polymorphism
class Father{
	private String name;
	private int age;

	public Father(){}

	public Father(String name,int age){
		this.name = name;
		this.age = age;
	}

	public void say(){
		System.out.println("I am your father!");
	}

	public String getName(){
		return name;
	}

}

class Son extends Father{

	public Son(String name,int age){
		super(name,age);
	}
	public Son(){

	}

	// If the attribute in the parent class has been assigned, the private attribute of the parent class can be obtained through the get method in the child class
	public void fathername(){
		System.out.println("My father is " + super.getName());
	}

	public void say(){
		System.out.println("I am Son");
	}

	public void power(){
		System.out.println("I will powerful than father!");

	}
}

1. Upward transformation

Format: parent variable name = new subclass ();

public class toUpDemo{
	public static void main(String[] args){

		// Transition up parent = child instance
		Son son = new Son("lgt",23);
		Father father = son;
		father.say();
		// father.power();   Even if the parent class is transformed, it cannot call methods unique to the child class

	}
}


Output results: I am Son

Summary:

There are some shortcomings in the upward transformation. After the transformation, because the operation is the parent object, the new method defined in the subclass (subclass specific) cannot be found

2. Downward transformation

//Subclass = subclass instance

		Father father = new Father("xxx",23);
		Son son = father;
		son.say();

Output:
    
    toDownDemo.java:52: error: Incompatible types: Father Cannot convert to Son
                Son son = father;
                          ^
1 Errors
  • Obviously, it is impossible to copy the above writing directly
  • Downward transformation must be upward transformation, followed by forced transformation and downward transformation

    Father father = new Son("xxx",99);//Upward transformation first
    		Son son = (Son)father;
    		son.say();
    
Thinking: why should we transform downward? (important)
  • For subclass instance objects, first generate subclass instances, assign values to parent class references, and then forcibly transfer parent class references to child class references. Isn't that bullshit? Just don't transform subclass instances directly? What's the point of doing this?

>>Look at this example and you will know the role of downward transformation!

  • First of all, there is an abstract class of Electronics "electronic products". Now he has three children, namely Laptop (Laptop), Camera (Camera) and Gameplayer (game console)
  • There is an abstract method in Electronics, that is, Type (commodity category). Each child has a method Function (Function) different from the parent class
package com.lgt.Demo5;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;


//Electronic product abstract class
abstract class Electronics{
    private String name;
    private float price;

    public Electronics(String name, float price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public float getPrice() {
        return price;
    }

    //Commodity category
    public abstract void type();
}

// Computer
class Laptop extends Electronics{
    public Laptop(String name, float price) {
        super(name, price);
    }

    @Override
    public void type() {
        System.out.println("Type:  Person Laptop");
    }

    public void function(){
        System.out.println("Function:  Media editing, program development, entertainment, Internet surfing");
    }
}

//Camera class
class Camera extends Electronics{

    public Camera(String name,float price){
        super(name, price);
    }
    @Override
    public void type() {
        System.out.println("Type:  Professional Camera");
    }

    public void function(){
        System.out.println("Function:  Take photos vlog shot");
    }
}

//sporting facilities
class GamePlayer extends Electronics{
    public GamePlayer(String name,float price){
        super(name, price);
    }

    @Override
    public void type() {
        System.out.println("Type:  GamePlayer");
    }

    public void function(){
        System.out.println("Function:  Entertainment");
    }
}



Create a new class: Mypossession (my item)

  • Use a generic array to store all specific electronic products
//My belongings
class MyPossession{
    private List<Electronics> mylist = new ArrayList<Electronics>();

    public void add(Electronics electronics){
        mylist.add(electronics);
    }

    public int getListLentgh(){
        return mylist.size();
    }

    public Electronics getListItem(int flat){
        return mylist.get(flat);
    }

}

Requirements:

I want to print out the type name, price and Function of each item in the test class.

The first three items are not important. Pay attention to the following functions

Analysis: when storing instances of computers, cameras and game consoles in a collection, in order to prevent the trouble of inconsistent types, generic types are used here, and their parent type "Electronics" is used to receive them uniformly, which is equivalent to an upward transformation; Through the upward transformation, we successfully store instances of different types in a generic collection, but there is also a problem, because the upward transformation refers to the parent class reference to the child class instance, so we use the parent class object in subsequent operations, so we cannot call the Function method unique to the child class

public class MyTest {
    public static void main(String[] args) {
        Laptop laptop = new Laptop("Macbook Pro",12229);
        Camera camera = new Camera("Z6",10999);
        GamePlayer gamePlayer = new GamePlayer("Xbox",2999);
        MyPossession myPossession = new MyPossession();
        myPossession.add(laptop);
        myPossession.add(camera);
        myPossession.add(gamePlayer);

        for(int i=0;i<myPossession.getListLentgh();i++){
            myPossession.getListItem(i).type();
            System.out.println("Name:  "+myPossession.getListItem(i).getName());
            System.out.println("Price:  "+myPossession.getListItem(i).getPrice());
            //myPossession.getListItem(i).function();   An error must be reported. It is not feasible to obtain the function method in a specific electronic product class here
            
            //Downward transformation format: subclass reference variable name = (subclass) parent class instance 
            if(myPossession.getListItem(i) instanceof Laptop){
                ((Laptop) myPossession.getListItem(i)).function();
            }
            else if(myPossession.getListItem(i) instanceof Camera){
                ((Camera) myPossession.getListItem(i)).function();
            }
            else{
                ((GamePlayer) myPossession.getListItem(i)).function();
            }
            System.out.println(">>-------------------");
        }
    }
}

((Laptop) myPossession.getListItem(i)).function();

This is equivalent to a downward transformation of the parent object, so that the function method can be called correctly.

//output
Type:  Person Laptop
Name:  Macbook Pro
Price:  12229.0
Function:  Media editing, program development, entertainment, Internet surfing
>>-------------------
Type:  Professional Camera
Name:  Z6
Price:  10999.0
Function:  Take photos vlog shot
>>-------------------
Type:  GamePlayer
Name:  Xbox
Price:  2999.0
Function:  Entertainment
>>-------------------

Process finished with exit code 0

Summary:

Whether it is upward or downward transformation, it is to flexibly deal with the diversity of classes in programming;

The upward transformation realizes that multiple subclasses can be referenced through the reference of a parent object;

Downward transformation, which is more applied to complex and diverse scenarios such as generic programming and collections

Topics: Java Polymorphism