当前位置:网站首页>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 .
边栏推荐
- How to use diff and patch to update the source code
- Canoe test: two ways to create CAPL test module
- Heartbeat报错 attempted replay attack
- Dictionaries and collections
- 本地Mysql忘记密码的修改方法(windows)[通俗易懂]
- How to quickly parse XML documents through C (in fact, other languages also have corresponding interfaces or libraries to call)
- Deepmind proposed a Zuan AI, which specially outputs network attack language
- [Galaxy Kirin V10] [server] iSCSI deployment
- Virtual machine configuration network
- Introduction to canoe automatic test system
猜你喜欢

How to use diff and patch to update the source code

shell awk

Canoe test: two ways to create CAPL test module
![[Galaxy Kirin V10] [server] KVM create Bridge](/img/a4/a35a276d13e194cefc547607c59f00.jpg)
[Galaxy Kirin V10] [server] KVM create Bridge
![[Galaxy Kirin V10] [server] FTP introduction and common scenario construction](/img/ef/f0f722aaabdc2d98723cad63d520e0.jpg)
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction

Introduction to canoe automatic test system

Function introduction of canbedded component

F12 clear the cookies of the corresponding web address

Canoe - the second simulation project -xvihicle1 bus database design (operation)

Summary of several job scheduling problems
随机推荐
Elevator dispatching (pairing project) ②
Quick sort (C language)
MFC document view framework (relationship between classes)
Canoe test: two ways to create CAPL test module
[testing theory] thinking about testing profession
[Galaxy Kirin V10] [desktop] FTP common scene setup
/*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*/
Analysis function in SQL
VPS安装Virtualmin面板
[Galaxy Kirin V10] [desktop] cannot add printer
Learning XML DOM -- a typical model for parsing XML documents
Summary of automated testing framework
Heartbeat启动后无反应
Using SA token to solve websocket handshake authentication
software test
[Galaxy Kirin V10] [server] NFS setup
The most ideal automated testing model, how to achieve layering of automated testing
Appscan installation error: unable to install from Net runtime security policy logout appscan solution
20 minutes to learn what XML is_ XML learning notes_ What is an XML file_ Basic grammatical rules_ How to parse
Notes on writing test points in mind mapping