当前位置:网站首页>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 .
边栏推荐
- Installation of ES plug-in in Google browser
- [untitled]
- [Galaxy Kirin V10] [server] iSCSI deployment
- Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
- shell awk
- Canoe test: two ways to create CAPL test module
- [test theory] test process management
- Canoe - the second simulation engineering - xvehicle - 2panel design (principle, idea)
- VPS安装Virtualmin面板
- Regular expression
猜你喜欢
Linked list operation can never change without its roots
Open the neural network "black box"! Unveil the mystery of machine learning system with natural language
[Galaxy Kirin V10] [server] soft RAID configuration
Knapsack problem and 0-1 knapsack problem
Fundamentals of software testing
Introduction to canoe automatic test system
Article publishing experiment
Introduction to tree and binary tree
Canoe - the third simulation project - bus simulation-1 overview
[Galaxy Kirin V10] [server] failed to start the network
随机推荐
/*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
Read a piece of text into the vector object, and each word is stored as an element in the vector. Convert each word in the vector object to uppercase letters. Output the converted elements in the vect
Canoe - the third simulation project - bus simulation - 3-2 project implementation
iptables导致Heartbeat脑裂
[advantages and disadvantages of outsourcing software development in 2022]
Interview and lecture summary 1
[test theory] test phase analysis (unit, integration, system test)
/*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*/
MFC document view framework (relationship between classes)
Crawl Zhejiang industry and trade news page
Oracle11g | getting started with database. It's enough to read this 10000 word analysis
Seven examples to understand the storage rules of shaped data on each bit
Canoe: the fourth simulation project -- bug debugging experience
F12 clear the cookies of the corresponding web address
20 minutes to learn what XML is_ XML learning notes_ What is an XML file_ Basic grammatical rules_ How to parse
software test
Virtual machine configuration network
PHP programming language (1) - operators
Recursive method to achieve full permutation (C language)
Linked list operation can never change without its roots