Workaround for abstract attributes in Java
Posted
by deamon
on Stack Overflow
See other posts from Stack Overflow
or by deamon
Published on 2010-05-12T14:44:34Z
Indexed on
2010/05/12
15:24 UTC
Read the original article
Hit count: 285
In Scala I would write an abstract class with an abstract attribute path
:
abstract class Base {
val path: String
}
class Sub extends Base {
override val path = "/demo/"
}
Java doesn't know abstract attributes and I wonder what would be the best way to work around this limitation.
My ideas:
a) constructor parameter
abstract class Base {
protected String path;
protected Base(String path) {
this.path = path;
}
}
class Sub extends Base {
public Sub() {
super("/demo/");
}
}
b) abstract method
abstract class Base { // could be an interface too
abstract String getPath();
}
class Sub extends Base {
public String getPath() {
return "/demo/";
}
}
Which one do you like better? Other ideas?
I tend to use the constructor since the path value should not be computed at runtime.
© Stack Overflow or respective owner