java - 关于抽象类的一个小问题
高洛峰
高洛峰 2017-04-17 13:38:34
0
3
509

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("嚎");
}
}
直接这样不好吗?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
大家讲道理

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:

class 别管我叫什么 {
    static void call(猫 cat) {
        cat.叫();
    }

    static void call(老虎 tiger) {
        tiger.叫();
    }
}

别管我叫什么.call(new 猫());
别管我叫什么.call(new 老虎());

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!

class 别管我叫什么 {
    static void call(猫科 cat) {
        cat.叫();
    }
}

别管我叫什么.call(new 猫());
别管我叫什么.call(new 老虎());

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!