I have a class, which we will call Entidad
like so:
public class Entidad {
protected String name;
protected String notes;
//Getters y setters
}
Of which 2 other classes extend, the first isPersona
public class Persona extends Entidad {
private String dni;
//Getters and setters
}
ANDInstitucion
public class Institucion extends Entidad {
private String cif;
//Getters and setters
}
The fact is that I have a table where I show different records and in the code I only use entity, would there be a way to show this:
<td th:text="${entidad.dni}"></td>
<td th:text="${entidad.cif}"></td>
In other words, if the element that has been added belongs to the person class, it shows the DNI and if it is from the Institution table, it shows the CIF without having to check in the Java code if it is an entity or another or without having to put a flag to check.
I don't know if this is what you are looking for, as there are parts of your question that make me wonder.
You can use something like this (adapting it):
either
I think you are not taking advantage of the base class. Both classes have something in common which is their identification number (or document number) even though they are of different types (DNI, CIF) The correct thing in my opinion is this base class:
Where the person class will force the type to DNI and Institution to CIF.
Another alternative is to create an abstract class called Document and that each subclass represents a specific type of document with its characteristics and that the ToString() method of each class knows how to represent the document in a String.
This way there are no conditionals you have to put in to distinguish one class from another when printing a property that both types have in common. The classes would then look like this:
Generic classes could also be used, but I think that's fine.
Using polymorphism, the first thing is that the parent is abstract , and declare an abstract method that forces you to implement it in those that inherit:
sons
The other:
To display the data, you just call the abstract method:
Depending on the object it is, it will print the DNI or the CIF.