当前位置:网站首页>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 .
边栏推荐
- /*The rewriter outputs the contents of the IA array. It is required that the type defined by typedef cannot be used in the outer loop*/
- [Galaxy Kirin V10] [desktop] cannot add printer
- Seven examples to understand the storage rules of shaped data on each bit
- CAPL: on sysVar_ Update difference on sysvar
- Canoe - the third simulation project - bus simulation-1 overview
- 三立期货安全么?期货开户怎么开?目前期货手续费怎么降低?
- 本地Mysql忘记密码的修改方法(windows)[通俗易懂]
- 20 kinds of hardware engineers must be aware of basic components | the latest update to 8.13
- Canoe - the second simulation project -xvihicle1 bus database design (operation)
- F12 clear the cookies of the corresponding web address
猜你喜欢
[Galaxy Kirin V10] [server] KVM create Bridge
Notes on writing test points in mind mapping
Canoe - the second simulation engineering - xvehicle - 2 panel design (operation)
TS type gymnastics: illustrating a complex advanced type
[Galaxy Kirin V10] [desktop] cannot add printer
Failed to configure a DataSource: ‘url‘ attribute is not specified... Bug solution
[Galaxy Kirin V10] [desktop] FTP common scene setup
Huge number multiplication (C language)
Function introduction of canbedded component
JMeter assembly point technology and logic controller
随机推荐
Jemeter plug-in technology
Basic function exercises
Deepmind proposed a Zuan AI, which specially outputs network attack language
Analysis function in SQL
Failed to configure a DataSource: ‘url‘ attribute is not specified... Bug solution
Huge number (C language)
Interview and lecture summary 1
VPS安装Virtualmin面板
Canoe - the second simulation engineering - xvehicle - 2 panel design (operation)
[Galaxy Kirin V10] [desktop] printer
/*Rewrite the program, find the value of the element, and return the iterator 9.13: pointing to the found element. Make sure that the program works correctly when the element you are looking for does
Capl: timer event
Canoe: the fourth simulation project -- bug debugging experience
The last month before a game goes online
Communication layer of csframework
[Galaxy Kirin V10] [server] failed to start the network
[Galaxy Kirin V10] [server] system startup failed
Get the data of the top 100 headlines today with Tianxing data
Advanced order of function
JMeter correlation technology