当前位置:网站首页>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 .
边栏推荐
- [算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
- Interview Essentials: talk about the various implementations of distributed locks!
- Fgui project packaging and Publishing & importing unity & the way to display the UI
- 堆排序【手写小根堆】
- Answer to "software testing" exercise: Chapter 1
- TYUT太原理工大学2022软工导论大题汇总
- [algorithm] sword finger offer2 golang interview question 6: sum of two numbers in the sorting array
- [算法] 剑指offer2 golang 面试题10:和为k的子数组
- Error: symbol not found
- Mixed use of fairygui button dynamics
猜你喜欢
平衡二叉树详解 通俗易懂
[algorithm] sword finger offer2 golang interview question 12: the sum of the left and right sub arrays is equal
阿里云微服务(一)服务注册中心Nacos以及REST Template和Feign Client
抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
What are the advantages of using SQL in Excel VBA
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
121道分布式面试题和答案
2-year experience summary, tell you how to do a good job in project management
堆排序【手写小根堆】
阿里云微服务(四) Service Mesh综述以及实例Istio
随机推荐
Mixed use of fairygui button dynamics
Role movement in the first person perspective
[Chongqing Guangdong education] Shandong University College Physics reference materials
错误: 找不到符号
Implementation of Excel import and export functions
[Yu Yue education] guide business reference materials of Wuxi Vocational and Technical College of Commerce
Detailed explanation of balanced binary tree is easy to understand
Alibaba cloud side: underlying details in concurrent scenarios - pseudo sharing
GPS高程拟合抗差中误差的求取代码实现
阿里云微服务(一)服务注册中心Nacos以及REST Template和Feign Client
记录:下一不小心写了个递归
Fairygui bar subfamily (scroll bar, slider, progress bar)
[算法] 剑指offer2 golang 面试题13:二维子矩阵的数字之和
Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
First acquaintance with C language (Part 2)
What are the advantages of using SQL in Excel VBA
Dark chain lock (lca+ difference on tree)
国企秋招经验总结
记录:Navicat Premium初次无法连接数据库MySQL之解决
2-year experience summary, tell you how to do a good job in project management