Java polymorphism first-time experience this article is intended for beginners of Java. We often see that Java is polymorphism in teaching materials, but general textbooks only stay in theory and there are few practical operations. Now I will briefly describe the concept of polymorphism in the Code. Due to my limited level, it is inevitable that there are deficiencies.
First of all, we have several types of computers, PCs, and laptops.
Java code
Class Computer {
Public void turnOn (){
}
}
Now we have computers, so personal PCs and laptops all inherit from them.
Java code
Class PC extends Computer {
Public void turnOn (){
System. out. println ("PC has turn on ");
}
}
Class NB extends Computer {
Public void turnOn (){
System. out. println ("NB has turn on ");
}
}
We can see that each class has a turnOn () method, but in the parent class, this method is empty, and the sub-classes have different implementations, which may not be obvious here. If there is another method that accepts these classes as parameters, just like this
Java code
Class Test {
Public void go (Computer computer ){
Computer. turnOn ();
}
}
This method receives base class parameters. Of course we can pass sub-classes to the method. We should also do this.
Java code
Go (new PC ());
Go (new NB ());
In this way, he will call the turnOn () method of the specific subclass, so the output of these two calls is different. if we want to call the turnOn () method of each subclass without using the base class as the parameter, we need to get the go () method with the same two methods bodies and receive the overload of different parameters.
Java code
Public void go (PC computer ){
Computer. turnOn ();
}
Public void go (NB computer ){
Computer. turnOn ();
}
This is also true, but it will produce a lot of repeated code and is not easy to maintain. Of course, this is only the most basic part of polymorphism. the Java polymorphism mechanism also has many features, for these suggestions, let's take a look at the think in java book, which describes in detail. Here we just briefly describe it and hope you will not laugh at it.