当前位置:网站首页>Inheritance and polymorphism (Part 2)
Inheritance and polymorphism (Part 2)
2022-07-06 13:08:00 【犇犇犇犇犇犇犇】
Inheritance and polymorphism
Catalog :
List of articles
- Inheritance and polymorphism
- 2. polymorphic :yum:
- 2.1 The concept of polymorphism :artificial_satellite:
- 2.2 The condition of polymorphism :artificial_satellite:
- 2.3 rewrite :artificial_satellite:
- 2.4 Transition up and down :artificial_satellite:
- 2.5 Advantages and disadvantages of polymorphism :artificial_satellite:
- 2.6 Try to avoid rewriting in construction methods :artificial_satellite:
Undertake the last time
1.9proteced keyword
1.10 Inheritance mode
- Single inheritance
class A{
}
class B extends A{
}
- Multiple inheritance
class A{
}
class B extends A{
}
class C extends B{
}
- Different classes inherit the same class
class A{
}
class B extends A{
}
class C extends A{
}
1.11final keyword
final int Size = 10 // Constant ;
final class B extend A {}
// Sealing class : Indicates that this class can no longer be inheritedfinal Modification methods // Sealing method : Represents that this method cannot be overridden
1.12 Inheritance and combination
Inheritance is is - a The relationship between
- For example, dogs are animals
The combination is has a or a part of
For example, the school is composed of students and teachers
class Student{ } class Teacher{ } class School{ private Student[] students; private Teacher[] teachers; }
2. polymorphic
2.1 The concept of polymorphism
The concept of polymorphism : Generally speaking , It's a lot of forms , The specific point is to complete a certain behavior , When different objects are completed, they will produce different results The state of .
2.2 The condition of polymorphism
Complete the upward transformation
Direct assignment
Animal animal = new Bird(" Parrot ",2);
The transmission of the method
public static void func1(Animal animal){ } public static void main(String[] args) { Bird bird = new Bird(" Parrot ",2); func1(bird); }
Return value of method
public static Animal func2(){ return new Bird(" Parrot ",2); }
Complete method rewrite
Call this overridden method through the reference of the parent class ( Dynamic binding )
2.3 rewrite
Meet the conditions of method rewriting
- Same method name
- The parameter list of the method is the same 【 Number , type , The order 】
- Method returns the same value
- Covariant type : The return value of the subclass and the return value of the parent class can also be parent-child relationship
- static Methods that modify cannot be overridden
- private Methods that modify cannot be overridden
- The access modifier of the subclass must be greater than or equal to the access modifier of the parent class
The difference between rewriting and overloading
type heavy load rewrite parameter list Must be modified It must not be modified return type You can modify It must not be modified Access qualification modifier You can modify There must be no stricter restrictions Dynamic binding
class Animal{ private String name; private int age; public Animal(String name, int age) { this.name = name; this.age = age; //eat();-> The so-called dynamic binding can also occur , Don't write code like this in the future } } class Bird extends Animal{ public String wing; public Bird(String name, int age) { super(name, age); } public void fly(){ System.out.println(getName()+" Flying "); } @Override public void eat() { System.out.println(getName()+" Eat bird food "); } } public static void main(String[] args) { // Bird bird = new Bird(" Little bird ",3); // Animal animal = bird; // Reference to the parent class Objects that reference subclasses Animal animal = new Bird(" Parrot ",2); animal.eat();// Dynamic binding Will output subclasses eat // animal.fly();// Can't call At this time, the parent class references , You can only call your own methods , Subclass methods cannot be called // animal.wing; }
Static binding : For example, method overloading
2.4 Transition up and down
2.4.1 Upward transformation
It has been introduced in the condition of polymorphism
2.4.2 Move down
** The downward transition is very unsafe , no need **
public static void main(String[] args) {
Animal animal = new Dog(" Dog ",3);
if(animal instanceof Bird){
// Not all animals are birds
Bird bird = (Bird)animal;
bird.fly();
}
}
public static void main5(String[] args) {
Animal animal = new Bird(" Bird ",3);
Bird bird = (Bird)animal;// Move down
bird.fly();
}
2.5 Advantages and disadvantages of polymorphism
【 The benefits of using polymorphism 】
- It can reduce the of code “ Cyclomatic complexity ”, Avoid using a lot of if - else
- More scalable
- If you want to add a new shape , The cost of code changes using polymorphism is also relatively low .
public static void drawMap3(){
Rect rect = new Rect();
Cycle cycle = new Cycle();
Flower flower = new Flower();
Shape[] shapes = {
cycle, rect, cycle, rect, flower};
for (Shape shape:shapes) {
shape.draw();
}
}
public static void drawMap2(){
Rect rect = new Rect();
Cycle cycle = new Cycle();
Flower flower = new Flower();
String[] shapes = {
"cycle", "rect", "cycle", "rect", "flower"};
for (String shape : shapes) {
if (shape.equals("cycle")) {
cycle.draw();
} else if (shape.equals("rect")) {
rect.draw();
} else if (shape.equals("flower")) {
flower.draw();
}
}
}
public static void main(String[] args) {
drawMap3();
}
【 Polymorphic defects 】
The running efficiency of the code is reduced .
2.6 Try to avoid rewriting in construction methods
public Animal(String name, int age) {
this.name = name;
this.age = age;
//eat();-> The so-called dynamic binding can also occur , Don't write code like this in the future
}
class Bird extends Animal{
public String wing;
public Bird(String name, int age) {
super(name, age);
}
public void fly(){
System.out.println(getName()+" Flying ");
}
@Override
public void eat() {
System.out.println(getName()+" Eat bird food ");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Animal(" animal ",10);
// Animal animal = new Dog(" Dog ",3);
animal.eat();
}
}
Conclusion : “ Make the object work in the simplest way possible ”, Try not to invoke the method in the constructor. ( If this method is overridden by a subclass , Will trigger dynamic binding , But the subclass object has not been constructed yet ), There may be some hidden problems that are very difficult to find .
边栏推荐
- [algorithm] sword finger offer2 golang interview question 7: 3 numbers with 0 in the array
- Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
- Shortest Hamilton path (pressure DP)
- 记录:动态Web项目servlet访问数据库404错误之解决
- Devops' future: six trends in 2022 and beyond
- 继承和多态(下)
- Wechat applet development experience
- Application architecture of large live broadcast platform
- MySQL 三万字精华总结 + 面试100 问,吊打面试官绰绰有余(收藏系列
- TYUT太原理工大学2022软工导论考试题型大纲
猜你喜欢
121 distributed interview questions and answers
[algorithm] sword finger offer2 golang interview question 6: sum of two numbers in the sorting array
Interview Essentials: talk about the various implementations of distributed locks!
[算法] 剑指offer2 golang 面试题9:乘积小于k的子数组
[algorithm] sword finger offer2 golang interview question 1: integer division
The earth revolves around the sun
Answer to "software testing" exercise: Chapter 1
阿里云微服务(三)Sentinel开源流控熔断降级组件
面渣逆袭:Redis连环五十二问,三万字+八十图详解。
[algorithm] sword finger offer2 golang interview question 13: sum of numbers of two-dimensional submatrix
随机推荐
记录:newInstance()过时的代替方法
How to ensure data consistency between MySQL and redis?
Detailed explanation of balanced binary tree is easy to understand
121 distributed interview questions and answers
PRIDE-PPPAR源码解析
All in one 1405: sum and product of prime numbers
What are the advantages of using SQL in Excel VBA
[算法] 剑指offer2 golang 面试题2:二进制加法
面试必备:聊聊分布式锁的多种实现!
[rtklib] preliminary practice of using robust adaptive Kalman filter under RTK
TYUT太原理工大学2022软工导论简答题
[GNSS data processing] Helmert variance component estimation analysis and code implementation
抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
Exception: ioexception:stream closed
Tyut Taiyuan University of technology 2022 introduction to software engineering
[Chongqing Guangdong education] reference materials for regional analysis and planning of Pingdingshan University
[algorithm] sword finger offer2 golang interview question 13: sum of numbers of two-dimensional submatrix
[algorithm] sword finger offer2 golang interview question 6: sum of two numbers in the sorting array
What are the advantages of using SQL in Excel VBA
错误: 找不到符号