Fundamentals of Java: 19 object-oriented features -- polymorphism

1. Meaning and characteristics of polymorphism

(1) Polymorphism means that a name can have multiple semantics. In programming languages, polymorphism refers to "one definition, multiple implementations". For example, the operator "+" has multiple meanings. Which operation to perform depends on the operand type participating in the operation:

1+2 //Addition operator
"1" + "2" //String concatenation operation where the operand is a string

(2) Class polymorphism provides flexibility in member design and diversity in method execution. Embodiment in Java:

  • Object polymorphism: the reference of the parent class points to the object of the child class

(3) Java reference variables have two types: compile time and run-time. The compile time type is determined by the type used when declaring the variable, and the runtime type is determined by the object actually assigned to the variable. Abbreviation: when compiling, look at the left; When running, look to the right. If compile time type and run-time type are inconsistent, object Polymorphism occurs. In case of Polymorphism:

  • "Look at the left": look at the reference of the parent class (the parent class does not have the methods unique to the child class)
  • "Look at the right": it looks at the objects of subclasses (actually running the methods of subclasses overriding the parent class)

That is, polymorphic member methods:

  • Compile time: to check whether there is a method called in the class declared by the reference variable.
  • Runtime: calls the overriding method in the class to which the actual new object belongs.

(4) Polymorphism: it improves the commonality of code, which is often called interface reuse.
Premise: inheritance or implementation relationship is required; There are overrides of methods.
Member variable: it does not have polymorphism. It only depends on the class declared by the reference variable.
(5) Polymorphism of objects

  • In Java, the object of a subclass can be used instead of the object of a parent class
  • A variable can only have one definite data type
  • A reference type variable may point to (Reference) many different types of objects
Person p = new Student(); 
Object o = new Person();//Variable o of type Object, pointing to an Object of type Person 
o = new Student(); //Variable o of type Object, pointing to an Object of type Student

The subclass can be regarded as a special parent class, so the reference of the parent class type can point to the object of the subclass: upcasting.

(6) If a reference type variable is declared as the type of the parent class, but actually refers to a subclass object, the variable can no longer access the unique attributes and methods added in the subclass.

Student m = new Student(); 
m.school = "pku"; //Legal. The Student class has a school member variable 
Person e = new Student(); 
e.school = "pku"; //Illegal. The Person class has no school member variable

The attribute is determined at compile time. At compile time, e is of type Person, and there is no school member variable. Therefore, compilation error occurs.

2. Polymorphism application

(1) The formal parameter type declared by the method is the parent type. You can call the method with the object of the subclass as an argument.

public class Test { 
    public void method(Person e) { // ...... 
        e.getInfo(); 
    } 
    public static void main(Stirng args[]) { 
        Test t = new Test(); 
        Student m = new Student(); 
        t.method(m); // The object m of the subclass is passed to the parameter e of the parent type 
    } 
}

(2) Virtual method invocation

  • Normal method calls:
Person e = new Person(); 
e.getInfo(); 
Student e = new Student(); 
e.getInfo();

  • Virtual method call (polymorphic)
    A method with the same name and parameter as the parent class is defined in the subclass. In the case of polymorphism, the method of the parent class at this time is called a virtual method. The parent class dynamically calls the method belonging to the subclass according to the different subclass objects assigned to it. Such method calls cannot be determined at compile time.
Person e = new Student(); 
e.getInfo(); //Call the getInfo() method of the Student class

At compile time, e is of Person type, and the method call is determined at run time, so the getInfo() method of Student class is called—— Dynamic binding

  • Premise: the getInfo() method is defined in the Person class, and each subclass overrides getInfo().
  • Execution: in the case of polymorphism, the getInfo() method of the object is called, and the actual execution is the method overridden by the subclass.

3. instanceof operator

x instanceof A;//Check whether x is an object of class A, and the return value is boolean. 

It is required that the class to which x belongs and class A must be the relationship between A subclass and A parent class, or compilation errors will occur.
If x belongs to subclass B of class A, the value of x instanceof A is also true.

public class Person extends Object {...} 
public class Student extends Person {...} 
public class Graduate extends Person {...} 
public void method1(Person e) { 
    if (e instanceof Person) 
        // Handle Person class and its subclass object true
    if (e instanceof Student) 
        //Handling Student class and its subclass objects false
    if (e instanceof Graduate) 
        //Handling the Graduate class and its subclass objects false
}

4. Object type conversion (Casting)

Casts on Java objects are called shapes:

  • Type conversion from a child class to a parent class can be done automatically
  • Type conversion from a parent class to a child class must be implemented through modeling (CAST)
  • Conversion between reference types without inheritance is illegal
  • You can use the instanceof operator to test the type of an object before modeling

    Example 1:
public class ConversionTest { 
    public static void main(String[] args) { 
        double d = 13.4; 
        long l = (long) d; 
        System.out.println(l); 
        int in = 5; 
        // boolean b = (boolean)in; 
        Object obj = "Hello"; 
        String objStr = (String) obj; 
        System.out.println(objStr); 
        Object objPri = new Integer(5); 
        // So the ClassCastException exception is thrown when the following code runs 
        String str = (String) objPri; 
    } 
}

Example 2:

public class Test { 
    public void method(Person e) { 
        // Assume that there is no getschool() method in the Person class 
        // System Out Pritnln (e.getschool())// Illegal, compile time error 
        if (e instanceof Student) { 
            Student me = (Student) e; // Cast e to Student type 
            System.out.pritnln(me.getschool()); 
        } 
    } 
    public static void main(String[] args){ 
        Test t = new Test(); 
        Student m = new Student(); 
        t.method(m); 
    } 
}

Differences between inherited member variables and inherited methods:

//Parent class
class Base { 
    int count = 10; 
    public void display() { 
        System.out.println(this.count); 
    } 
}

//Subclass
class Sub extends Base { 
    int count = 20; 
    public void display() { 
        System.out.println(this.count); 
    } 
}
//Test class
public class FieldMethodTest { 
    public static void main(String[] args){ 
        Sub s = new Sub(); 
        System.out.println(s.count); //20 
        s.display(); //20
        Base b = s; 
        System.out.println(b == s); //true 
        System.out.println(b.count); //10
        b.display(); //20
    } 
}

If the subclass overrides the parent method, it means that the method defined in the subclass completely covers the method with the same name in the parent class, and the system will not be able to transfer the method in the parent class to the subclass.
For instance variables, there is no such phenomenon. Even if the instance variables exactly the same as the parent class are defined in the child class, it is still impossible for this instance variable to overwrite the instance variables defined in the parent class.

5. Polymorphic summary

(1) Three necessary conditions for the existence of polymorphism

  1. There should be inheritance;
  2. There should be rewriting;
  3. A parent class reference points to a child class object.

(2) There are two types of polymorphism:

  1. Compile time polymorphism
    For multiple methods with the same name, if it can be determined at compile time which one of the methods with the same name is executed, it is called compile time polymorphism.
  2. Runtime polymorphism
    It is called runtime polymorphism when it cannot be determined at compile time and only at run time can it be determined which of the multiple methods with the same name is executed.

(3) Class polymorphism expression

  1. Method overloading
    Overloads represent polymorphism of methods in the same class. A class with multiple overloaded methods provides multiple implementations for a function. During compilation, it determines which overloaded method should be executed according to the data type, number and order of the actual parameters of the method.
  2. Subclasses redefine members inherited from the parent class
    When the members inherited from the parent class are not suitable for the child class, the child class cannot delete them, but can redefine them to make the parent class members adapt to the new requirements of the child class. Subclasses redefine parent class members. Members with the same name show polymorphism between parent and child classes. Parent class objects refer to parent class members, and child class objects refer to child class members. There will be no conflict and confusion.
    A subclass can redefine a member variable of the parent class with the same name, which means that the subclass hides the member variable of the parent class. A subclass can also redefine a member method of the parent class with the same name. When the parameter list of a subclass method is exactly the same as that of a parent method, it is called a subclass method override parent method. When overriding a parent method, the access permission of the child method cannot be less than that of the parent method.
    Since the equals() method of the Object class compares whether the references of two objects are equal rather than whether the values are equal, a class should override the equals() method of the Object class and provide the method of comparing the equality of two objects of this class.
    Coverage is represented by the polymorphism of methods between parent and child classes. The principle of java for finding execution methods is: start from the class to which the Object belongs, and find the matching method for execution. If there is no matching method in the current class, then find the matching method in the parent class or ancestor class layer by layer until the Object class.

6. Use of Object class

(1) The Object class is the root parent of all Java classes.
If the extension keyword is not used in the class declaration to specify its parent class, the default parent class is java Lang.Object class.

public class Person { ... } 

Equivalent to:

public class Person extends Object { ... }

(2) = = operator and equals method
==:
Basic type comparison value, that is, as long as the values of two variables are equal, it is true.

int a=5; if(a==6){...}

Reference type comparison reference (whether it points to the same object): only when it points to the same object, = = returns true.

Person p1=new Person(); 
Person p2=new Person(); 
System.out.println(p1==p2)//false

When comparing with = =, the data types on both sides of the symbol must be compatible (except for the basic data types that can be automatically converted), otherwise the compilation error occurs.

equals():
All classes inherit from Object, so they get the equals () method. The equals () method can also be overridden. The equals() method can only compare reference types. Its function is the same as = = to compare whether it points to the same Object.
Syntax format:

obj1.equals(obj2)

Exceptions:
When the equals() method is used for comparison, for classes File, String, Date and Wrapper Class, the type and content are compared regardless of whether the referenced object is the same;
Reason: the equals() method of the Object class is overridden in these classes.
When the custom uses equals(), it can be overridden. Used to compare whether the contents of two objects are equal.

Principles for overriding the equals() method:
Symmetry: if x.equals(y) returns "true", then y.equals(x) should also return "true".
Reflexivity: x.equals(x) must return 'true'.
Transitivity: if x.equals(y) returns "true" and y.equals(z) returns "true", then z.equals(x) should also return "true".
Consistency: if x.equals(y) returns "true", as long as the contents of X and Y remain unchanged, no matter how many times you repeat x.equals(y), the return is "true".
In any case, x.equals(null) always returns "false"; x. Equals (objects of different types from x) always returns "false".

int it = 65; 
float fl = 65.0f; 
System.out.println("65 And 65.0f Are they equal? " + (it == fl)); //true


char ch1 = 'A'; 
char ch2 = 12; 
System.out.println("65 and'A'Are they equal?" + (it == ch1));//true 
System.out.println("12 and ch2 Are they equal?" + (12 == ch2));//true


String str1 = new String("hello"); 
String str2 = new String("hello"); 
System.out.println("str1 and str2 Are they equal?"+ (str1 == str2));//false
System.out.println("str1 whether equals str2?"+(str1.equals(str2)));//true
System.out.println("hello" == new java.util.Date()); //Compilation failed

(3) toString() method
The toString() method is defined in the Object class. Its return value is of type String. It returns the class name and its reference address.
The toString() method is automatically called when connecting a String with other types of data.

Date now=new Date();
System.out.println("now="+now); //Equivalent to the following statement 
System.out.println("now="+now.toString()); 

You can override the toString() method in user-defined types as needed
For example, the String class overrides the toString() method to return the value of the String.

s1="hello"; 
System.out.println(s1);//Equivalent to the following statement
System.out.println(s1.toString()); 

When the basic type data is converted to String type, the toString() method of the corresponding wrapper class is called

int a=10;
System.out.println("a="+a);

Posted by Liz_SA on Wed, 01 Jun 2022 04:30:55 +0530