I'm writing an abstract class and have some sub-classes extend it. I have the exact same method with the same implementation in the sub-classes, and I'm wondering if there's a way to avoid the code duplication. The problem is that although the code is completely identical in every class, it uses a static variable of the class. Is there a way to have the method written only once (in the abstract class, for example) and have the method access the static member "NAME
" from the class type of the current object?
In other words, is there a way to implement the method getName()
only once, and return the NAME
static variable of the current type of class?
public abstract class Car {
public abstract String getName();
}
public class Bus extends car{
private static final String NAME = "Bus a Bus A";
public String getName() {
return Bus.NAME;
}
}
public class Taxi extends car{
private static final String NAME = "TAXiiii";
public String getName() {
return Taxi.NAME;
}
}
public class Motor extends car{
private static final String NAME = "motor hehe";
public String getName() {
return Motor.NAME;
}
}
Why not simply pass the name to the super constructor? Although this removes the need for Car
to be abstract
, because you can simply return the name from its getName
method instead.
public class Car {
private final String name;
public Car(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Bus extends Car {
private static final String NAME = "Bus a Bus A";
public Bus() {
super(NAME);
}
}
public class Taxi extends Car {
private static final String NAME = "TAXiiii";
public Taxi() {
super(NAME);
}
}
public class Motor extends Car {
private static final String NAME = "motor hehe";
public Motor() {
super(NAME);
}
}