如何以及何时使用抽象类 [英] How and when to use an abstract class

查看:37
本文介绍了如何以及何时使用抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 Java 测试程序.我想知道这里有多少抽象类更重要,为什么我们为此使用抽象类.

This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

是强制性的还是最好的方法;如果是这样怎么办?

Is it a mandatory or is it best method; if so how?

class Shape1 {
    int i = 1;
    void draw() {
        System.out.println("this is shape:" + i);
    }
}

class Shape2 {
    int i = 4;
    void draw() {
        System.out.println("this is shape2:" + i);
    }
}


class Shape {
    public static void main(String args[]) {
        Shape1 s1 = new Shape1();
        s1.draw();

        Shape2 s2 = new Shape2();
        s2.draw();
    }
}

推荐答案

您将在此处使用抽象类或接口,以便创建提供 void draw() 方法,例如

You'd use an abstract class or interface here in order to make a common base class/interface that provides the void draw() method, e.g.

abstract class Shape() {
  void draw();
}

class Circle extends Shape {
   void draw() { ... }
}

...

Shape s = new Circle();
s.draw();

我通常会使用接口.但是,如果出现以下情况,您可能会使用抽象类:

I'd generally use an interface. However you might use an abstract class if:

  1. 您需要/想要提供通用功能或类成员(例如,您的案例中的 int i 成员).
  2. 你的抽象方法除了公共访问(这是接口允许的唯一访问类型)之外还有其他任何东西,例如在我的示例中,void draw() 将具有包可见性.
  1. You need/want to provide common functionality or class members (e.g. the int i member in your case).
  2. Your abstract methods have anything other than public access (which is the only access type allowed for interfaces), e.g. in my example, void draw() would have package visibility.

这篇关于如何以及何时使用抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆