I have a class CommonTableModel that has several instance methods and each operate on the two instance variables
- columnNames
- data
Now, I have six tables, each has diff. column names but should have all the instance methods of the CommonTableModel class. So to pass an instance of the CommonTableModel to a JTable instance, I should first initialize both of the instance variables (columnNames and data).
Q1. Should I make six TableModels, each corresponding to each table and then extends them to the CommonTableModel?
public class FirstTableModel extends CommonTableModel {
public FirstTableModel() {
columnNames = {"id", "name"};
data = {{1, "John"}};
}
}
In the above example, I tried to initialize inherited data members so that each of the six TableModel can populate columnNames according to the table that they denote.
But I got an error which is restricting me to initialize the inherited members in this way. I think that we can’t initialize instance variables in this way.
Then how can I populate the instace variables of CommonTableModel so that the instance methods of the CommonTableModel process the data that I populate them later.
One of the solution is to pass the data in the constructor of CommonTableModel but in that way, I will have to pass the whole columnNames each time when I make a Table.
I am very confused as I don’t have much experience in programming and don’t know good coding practices.
Please, also refer some good design pattern books so that I can have a better understanding of design patterns.
Arrays which aren’t initialized with
neware array constants. You can only initialize them directly after declaration. E.g.Thus, you should replace the particular lines by (assuming those are already
protectedfields ofCommonTableModel):Edit as per the comments: you can of course also define a constructor for that and make use of the
super()call. The advantage is that this improves the degree of encapsulation, i.e. you don’t need to declare the fieldsprotected, but they can now be declaredprivate. Here’s a kickoff example:.
Note that you still need the
newkeyword to instantiate them (rsp was wrong here in his answer). You should only NOT make the propertiesstatic!! It would affect every instance of the same class. You really don’t want to have that. Also see my comment here below.