abstract class 猫科{
abstract void 叫();
}
class 猫 extends 猫科{
void 叫(){
System.out.println("喵");
}
}
class 老虎 extends 猫科{
void 叫(){
System.out.println("嚎");
}
}
为什么多此一举的去定义一个抽象类呢?
class 猫{
void 叫(){
System.out.println("喵");
}
}
class 老虎{
void 叫(){
System.out.println("嚎");
}
}
直接这样不好吗?
Java beginner, some insights:
First of all, let’s talk about the concept of high-end. The former is usually called design pattern
策略模式
;Let’s talk about the scenarios corresponding to this mode:
What if one of your classes now wants to call the
猫
methods of老虎
and叫
? Use the definition method you have later:Oops, I have to write the same code twice! Now that the amount of code is small, I can still write it without worrying about trouble. What if the code is large? Not only is it laborious to write, but it is also disgusting to maintain!
Okay, now
策略模式
will liberate you!It’s very simple! It’s easy to write! Anyone who maintains this code will thank you silently in their hearts!
================================================== ==============
It’s just that the boss will be unhappy: I gave you so much money, so why don’t you just write these lines of code for me?!
Used to ensure that all cats can bark
Without this abstract class, who knows whether the cat and tiger you defined will bark
The common features of subclasses are all implemented in abstract classes, and subclasses do not need to implement them repeatedly
At the same time, abstract methods can also be defined to express some similar behaviors but in different forms, forcing subclasses to implement specific implementations
Purpose: To make subclasses show the same behavioral interface, but the specific expression forms are different