简体   繁体   English

抽象类用法

[英]Abstract class usage

When using abstract classes in an application, I came across two possible ways to access data in abstract classes. 在应用程序中使用抽象类时,我遇到了两种可能的方法来访问抽象类中的数据。 Would one be preferred over the other because of its context of being an within an abstract class? 是否因为一个抽象类的上下文而优先于另一个?

public abstract class Example {

       private String name;

       public Example(String name) {
            this.name = name;
       }

       //other methods that can be overridden in child classes
}

public class ExampleTwo extends Example {

       public ExampleTwo() {
            super("ExampleTwo");
       }
}

or would it be better to simply override a returning method with a value, given the same output. 还是在给定相同输出的情况下,简单地用值覆盖返回方法。 For example: 例如:

public abstract class Example {

       public abstract String getName();

       //other methods that can be overridden in child classes
}

public class ExampleTwo extends Example {

       @Override
       public String getName() {
             return "ExampleTwo";
       }

}

You're describing two different scenarios. 您正在描述两种不同的情况。 In the first name is a variable which is set in the constructor and read with its getter. 第一个name是一个变量,该变量在构造函数中设置并使用其getter读取。 The second defines a getName method which can return anything, eg a random string. 第二个定义了一个getName方法,该方法可以返回任何内容,例如随机字符串。

Well, for a start, these two approaches are completely different from one another. 首先,这两种方法是完全不同的。 Your first example will never expose your name variable to its children since it's private . 第一个示例永远不会将name变量公开给它的子级,因为它是private Your second example mandates that every child implements getName as part of its API. 您的第二个示例要求每个孩子都将getName作为其API的一部分来实现。

Ultimately it depends on what you want to accomplish. 最终,这取决于您要完成什么。

In the first case I would presume that you're establishing some kind of conventional state for your classes, and your children needed to supply the parent with a bit of metadata so that the parent's methods could respond correctly. 在第一种情况下,我假设您正在为类建立某种常规状态,并且您的孩子需要向父级提供一些元数据,以便父级的方法可以正确响应。 Think of an Animal hierarchy; 想想动物等级制度; you'd define makeSound in the parent, but each child would tell it how to speak. 您可以在父makeSound中定义makeSound ,但每个孩子都会告诉它如何说话。

In the second case I'd favor an interface over abstract classes, as you're not getting any wins from inheritance in that approach. 在第二种情况下,我更喜欢使用接口而不是抽象类,因为在这种方法中继承不会带来任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM