I have a generic Employee class and 3 other specific classes that inherit from Employee. Within the Employee class, I have the toString method.
abstract class Funcionario {
private String nome;
private String documento;
public String toString(){
return "\nNome e Documento";
}
}
class Motorista extends Funcionario {
private String cnh;
public String toString(){
return "CNH";
}
}
class Secretaria extends Funcionario {
private String telefone;
public String toString(){
return "Telefone";
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Secretaria fulana = new Secretaria();
System.out.println(fulana);
Secretaria ciclana = new Secretaria();
System.out.println(ciclana);
Motorista beltrano = new Motorista();
System.out.println(beltrano);
}
}
There are other classes that also inherit from Officer . Is there a way, (maybe by polymorphism) that I can 'iterate' over all objects and execute the toString method of each?
Instead of calling one object at a time within System.out.print
, is there any way to save code?
Link to Ideone Code here .