I have read many posts and articles and now understood that static methods can not be inherited. To explain my issue, you can look at the following pieces of code:
The main class:
public class DataTable {
public String id;
public String date;
public String reserve() throws SQLException {
......
String query="insert into `" + this.getClass().getSimpleName() +"`() values ()";
........
String key = ......
.......
return key;
}
}
One of the subclasses:
public class Contact extends DataTable{
public String firstName;
public String lastName;
public String phoneNumber;
...........
}
With this, if I need at some point of time to reserve a contact, I would need to write:
Contact contact=new Contact();
String id = contact.reserve();
This works. But I find it is not optimal. To me ,the first line is completely useless. I would much prefer writing:
String id = Contact.reserve();
The code would be cleaner and I would guess that it would use less resources at runtime, as it wouldn't have to create an instance of Contact which we really don't need. But for that, I should either:
- Create a specific reserve() static method in each subclass and remove it from the main class. I really don't think it is any better, as I would have the exact same piece of code in a big number of classes;
- or make reserve() static in the main class, and allow it to access the classname from which it was called, which does not seem feasible in java.
I hope my question is clear enough. Any ideas on how to handle that? Or should I just keep it as it is?
Contactif needed for specificreserveimplementation. Or even better: have it as a utility method and pass the required parameters instead of making suchstaticinheritance.