Reputation: 55
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";
}
}
Upvotes: 1
Views: 74
Reputation: 106430
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.
Upvotes: 1
Reputation: 8728
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, e.g. a random string.
Upvotes: 1