简体   繁体   中英

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. The second defines a getName method which can return anything, eg a random string.

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 . Your second example mandates that every child implements getName as part of its 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.

In the second case I'd favor an interface over abstract classes, as you're not getting any wins from inheritance in that approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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