当前位置:网站首页>Polymorphic system summary

Polymorphic system summary

2022-07-04 10:58:00 Black demon fairy moon

One 、 polymorphic
Polymorphism can be divided into two kinds : One is method polymorphism , The other is object polymorphism
1. Method polymorphism
Method polymorphism can be divided into two kinds : One is overload , The other is rewriting
heavy load : In the same class , Same method name , The relationship between methods with different parameters , Take the following example to illustrate :

 public void f1() {
    
        System.out.println(" Ha ha ha , You are a little pig ");
    }
    public void f1(int x){
    
        System.out.println(" Ha ha ha ,x It's a little pig ");
    }

rewrite : Occurs in two parent and child classes , follow “ With two , A large , Two small rules ”, With two : The method names of subclasses and superclasses are the same 、 Same parameter list , A large : The modifier of the subclass is larger than that of the parent , Two small : The return value type of the subclass is smaller than that of the parent class , The exception thrown by the child class is smaller than that of the parent class

class Father{
    
    public void f1(int s)
    {
    
        System.out.println(" Parent class method ");
    }
}
class son extends Father{
    
    @Override
    public void f1(int s){
    
        System.out.println(" Subclass method ");
    }
}

2. Object polymorphism
The basis of object polymorphism is inheritance , There are two kinds of object polymorphism : Transition up and down
Upward transformation : Parent class Parent instance = Subclass instance ( Automatic conversion )
Move down : Subclass Subclass instance =( Subclass ) Parent instance ( Cast )
We need to pay attention to when we are actually programming :90% All of our programming is upward transformation , Only 10% The programming of is a downward transformation , Among them, the downward transformation is basically to add attributes and functions that the parent class does not have .
(1) Upward polymorphism

public class Test1 {
    
    public static void main(String[] args) {
    
        DataBaseMessage dbm=new DataBaseMessage();
        WebServerMessage wsm=new WebServerMessage();
        print(dbm);
        print(wsm);
    }
    public static void print(Message message){
    
        message.print();
    }

}
class Message{
    
    public void print(){
    
        System.out.println("www.mldn.cn");
    }
}
class DataBaseMessage extends Message{
    
    @Override
    public void print(){
    
        System.out.println("Oracle Database link information ");
    }
}
class WebServerMessage extends Message{
    
    @Override
    public void print(){
    
        System.out.println("Web Server link information ");
    }
}

summary : Upward polymorphism can complete the unification of method parameters ( Receive or return ), For example print In the method , We have only one type of parameter, which is message, But we can use DataBaseMessage, You can also use WebServerMessage. Upward polymorphism requires attention : Inherit + rewrite , Although it is a parent type , But the method of subclass is called .

 public static void print(WebServerMessage message){
    
        message.print();
    }
    public static void print(DataBaseMessage message){
    
        message.print();
    }

Someone may come up with : Why not use the method of function overloading ? In this way, you can also realize the corresponding functions, just like the code above , But we should also consider the maintainability of programming . If the method of function overloading is used , Add one... At a time Message Subclasses of , We need to write it again print Overload method of , This is very difficult to maintain !
(2) Downward polymorphism

public class Test2 {
    
    public static void main(String[] args) {
    
        Animal a=new Cat();
        a.eat();
    }
    
}
class Animal{
    
    public void eat(){
    
        System.out.println(" Small animals can eat anything ");
    }
}
class Cat extends Animal{
    
    public void play(){
    
        System.out.println(" Kitty likes catching butterflies ");
    }
    public void eat(){
    
        System.out.println(" Xiaomiao likes to eat dried fish ");
    }
}

We can see from the above code that we are creating upward polymorphism ,Animal The reference variable of a Called Cat and Animal The common method , But what it does is Cat The function of is “ Xiaomiao likes to eat dried fish ”, But if you want to be Animal Type of a Realization Cat The unique method of play() What shall I do? ? Look at the code below :

public class Test2 {
    
    public static void main(String[] args) {
    
        Animal a=new Cat();
        a.eat();
        // Then add 
        Cat c=(Cat)a;
        c.play();
    }

}
class Animal{
    
    public void eat(){
    
        System.out.println(" Small animals can eat anything ");
    }
}
class Cat extends Animal{
    
    public void play(){
    
        System.out.println(" Kitty likes catching butterflies ");
    }
    public void eat(){
    
        System.out.println(" Xiaomiao likes to eat dried fish ");
    }
}

The running result of the program is :

 Xiaomiao likes to eat dried fish 
 Kitty likes catching butterflies 

Now someone may have doubts , Why don't I just create one Cat And then call this play() Methods? ? Let's look at the following example , We are Person1 Class Object Class equals Method , According to the rewritten condition equals Method parameters cannot be changed , So what must be passed in is object type , But the incoming obj We also want to use Person1 Inside name,age What about attributes ? We can use downward transformation !

class Person1 extends Object{
    
    String name;
    int age;
    @override
    public boolean equals(Object obj){
    
       /** *  Judge whether the two are the same class , such as pa.equals(" Dog ") */
     	 if(!(obj instanceof Person1)){
    
            return false;
        }
        /** *  Judge whether the incoming object is empty, that is null, In this case, a null pointer error will occur  */
        if(obj==null){
    
            return false;
        }
        /** *  Judge whether they are the same object  */
        if(this==obj){
    
            return true;
        }
        Person1 per = (Person1) obj;//obj There's no person Properties of , In order to obtain person Properties of 
        return this.name.equals(per.name)&&this.age==per.age;
    }

But what we need to pay attention to is , Only after the successful upward transformation can we transform downward , Otherwise, the following errors will appear : That is, types cannot be converted to each other

Exception in thread "main" java.lang.ClassCastException: cn.tedu.exercise1.Animal cannot be cast to cn.tedu.exercise1.Cat

summary : Downward polymorphic usage is mainly to increase the functions that the parent class and subclass do not , Two unrelated classes cannot complete downward polymorphism , You must complete up polymorphism before you can complete down polymorphism , Otherwise, there will be an exception that the type cannot be converted . In order to ensure the security of downward transformation, we introduce instanceof The concept of :
instranceof Usage of :

Instance name instanceof Class name :a instanceof A, The return value type is boolean

 Animal a=new Cat();
 System.out.println(a instanceof Cat);
 System.out.println(a instanceof Animal);

The result is the following code ,“instanceof” It is judgement. a yes A Example , We can see a yes Animal Example , It's also Cat Example

true
true

Then we use the following code when transforming downward :

    if(a instanceof Cat){
    
        Cat c=(Cat)a;
        c.play();
    }

We have now received a Animal Variable of type a, We want to use Cat Type of play Method , Let's judge first a Is it right? Cat Class instantiation , If we are going to make a downward transformation .

原网站

版权声明
本文为[Black demon fairy moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141412499957.html

随机推荐