当前位置:网站首页>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 .
边栏推荐
- [rtklib] preliminary practice of using robust adaptive Kalman filter under RTK
- Pride-pppar source code analysis
- 2-year experience summary, tell you how to do a good job in project management
- RTKLIB: demo5 b34f.1 vs b33
- Fairygui bar subfamily (scroll bar, slider, progress bar)
- 异常:IOException:Stream Closed
- Ten minutes to thoroughly master cache breakdown, cache penetration, cache avalanche
- Knowledge system of digital IT practitioners | software development methods -- agile
- 《软件测试》习题答案:第一章
- What are the functions and features of helm or terrain
猜你喜欢
![[Chongqing Guangdong education] Shandong University College Physics reference materials](/img/56/4ac44729c3e480a4f779d6a890363a.jpg)
[Chongqing Guangdong education] Shandong University College Physics reference materials
![[algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers](/img/64/0f352232359c7d44f12b20a64c7bb4.png)
[algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers

抽象类和接口

【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
![[算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等](/img/11/ee0628a68542236fc641966579a31a.png)
[算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等

面试必备:聊聊分布式锁的多种实现!

121 distributed interview questions and answers

C code implementation of robust estimation in rtklib's pntpos function (standard single point positioning spp)

面渣逆袭:Redis连环五十二问,三万字+八十图详解。

国企秋招经验总结
随机推荐
抽象类和接口
Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
Sharing ideas of on-chip transplantation based on rtklib source code
记录:Navicat Premium初次无法连接数据库MySQL之解决
Lean product development - Lean Software Development & lean product development
[Chongqing Guangdong education] reference materials for regional analysis and planning of Pingdingshan University
[algorithm] sword finger offer2 golang interview question 9: subarray with product less than k
Chromatic judgement bipartite graph
Ten minutes to thoroughly master cache breakdown, cache penetration, cache avalanche
PRIDE-PPPAR源码解析
TYUT太原理工大学2022“mao gai”必背
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
TYUT太原理工大学2022软工导论简答题
2年经验总结,告诉你如何做好项目管理
[rtklib 2.4.3 B34] version update introduction I
阿里云微服务(二) 分布式服务配置中心以及Nacos的使用场景及实现介绍
图书管理系统小练习
基本Dos命令
Pride-pppar source code analysis
rtklib单点定位spp使用抗差估计遇到的问题及解决