I have the following pseudo-code in java:
class MyClassSuper{
public static final String VALUE = "e";
}
class MyClassSub extends MyClassSuper{
public static final String VALUE = "f";
}
class MyGenericClass {
public void print(){
System.out.println(T.VALUE);
}
}
When I create a new instance of MyGenericClass with MyClassSub as its type I'm expecting the print method to print "f", but it prints "e" instead. Is it possible to have MyGenericClass treat T as the actual type that it is while keeping the super class that T extends currently ?
EDIT:
Actual code (abbreviated):
public class Bean implements Serializable {
public static final String FILE_EXT = "";
private static final long serialVersionUID = 1L;
}
public class UserBean extends Bean{
public static final String FILE_EXT = "u";
private static final long serialVersionUID = 1L;
private String name;
public UserBean(String name){
this.name = name;
}
}
public class BeanPersistence implements IBeanPersistence {
public void printExtension(){
System.out.println(T.FILE_EXT);
}
}
That is the code I'm trying to write. Basicly I want the BeanPersistence class to know what extension to use for the file it is writing, based on the type of Bean it was initialized with. From the comments I gather this is the wrong way of doing this, what would be the appropriate way ? (Obviously the printExtension method is just there to test)
解决方案
This might be suitable, depending on your case.
public class BeanPersistence {
public void printExtension(Bean bean) {
System.out.println(bean.getExtension());
}
public static void main(String[] args) {
BeanPersistence persistence = new BeanPersistence<>();
UserBean userBean = new UserBean();
AdminBean adminBean = new AdminBean();
persistence.printExtension(userBean); // prints u
persistence.printExtension(adminBean); // prints a
}
}
abstract class Bean {
abstract String getExtension();
}
class UserBean extends Bean {
private static final String FILE_EXT = "u";
@Override
String getExtension() {
return FILE_EXT;
}
}
class AdminBean extends Bean {
private static final String FILE_EXT = "a";
@Override
String getExtension() {
return FILE_EXT;
}
}
In general you should access object properties through methods, not directly. When we call methods, object-oriented behaviour (polymorphism, dynamic dispatch) will invoke the right method.
See also