I have a question on how to call an objects base member when instantiated through an interface.
Suppose I have the following interface and concrete classes in a framework I am trying to build:
public interface UsedClass {
public boolean getBool();
}
public class User implements UsedClass {
private String userName;
private String userRole;
public User(String userName, String userRole){
this.userName = userName;
this.userRole = userRole;
}
public boolean getBool() {
// some code
}
public int getUserName() {
return userName;
}
public int getUserRole() {
return userRole;
}
And an implementing class:
public class Run implements UsedClass {
private String runName;
private int runNumber;
public Run(String runName, int runNumber){
this.runName = runName;
this.runNumber = runNumber;
}
public boolean getBool() {
// some code
}
public String getRunName() {
return runName;
}
public int getRunNumber() {
return runNumber;
}
}
But I cannot put methods getRunName() or getUserRole() into the interface!
The end goal is to create a FactoryClass to handle the objects passed from a database GUI.
I would like to know if there is a better way then using class reference be able to safely call methods of Run or User such as:
public class EntityFactory {
public static Object getValueAt(int rowIndex, int columnIndex, UsedClass usedClass) {
if (usedClass.getClass().getSimpleName().equals("User")) {
switch (columnIndex) {
case 0:
return ((User) usedClass).getUserName();
case 1:
return ((User) usedClass).getUserRole();
default:
return null;
}
} else if (usedClass.getClass().getSimpleName().equals("Run")) {
switch (columnIndex) {
case 0:
return ((Run) usedClass).getRunName();
case 1:
return ((Run) usedClass).getRunNumber();
default:
return null;
}
}
I have read several SO posts type casting when objects are of interface references in Java and Java cast interface to class
where it is implied that reference casting is not advised, but since I cannot put all methods into the interface, what would be advised?
usedClass instanceof Userinstead ofusedClass.getClass().getSimpleName().equals("User").getValueAt(int columnIndex)method in the interface and implement it in subclasses ?instanceofgarbage.