Home  >  Q&A  >  body text

java - 关于抽象类的一个小问题

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

高洛峰高洛峰2710 days ago519

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:40:34

    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?!

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:40:34

    Used to ensure that all cats can bark

    Without this abstract class, who knows whether the cat and tiger you defined will bark

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:40:34

    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

    reply
    0
  • Cancelreply