En Java, las variables que contienen objetos son variables polimórficas.
El término polimórfico (literalmente: muchas formas) se refiere al
hecho de que una misma variable puede contener objetos de diferentes
tipos (del tipo declarado o de cualquier subtipo del tipo declarado). El
polimorfismo aparece en los lenguajes orientados a objetos en numerosos
contextos, las variables polimórficas constituyen justamente un primer
ejemplo.
Observemos la manera en que el uso de una variable polimórfica nos ayuda a simplificar nuestro método listar. El cuerpo de este método es:
for (Elemento elemento : elementos)
elemento.imprimir();
elemento.imprimir();
En
este método recorremos la lista de elementos (contenida en un ArrayList
mediante la variable elementos), tomamos cada elemento de la lista y
luego invocamos su método imprimir.El
uso de herencia en este ejemplo ha eliminado la necesidad de escribir
dos ciclos en el método listar. La herencia evita la duplicación de
código no sólo en las clases servidoras sino también en las clases
clientes de aquellas.
public class CD
{
private String title;
private String artist;
private String comment;
CD(String theTitle, String theArtist)
{
title = theTitle;
artist = theArtist;
comment = " ";
}
void setComment(String newComment)
{ ... }
String getComment()
{ ... }
void print()
{ ... }
...
}
{
private String title;
private String artist;
private String comment;
CD(String theTitle, String theArtist)
{
title = theTitle;
artist = theArtist;
comment = " ";
}
void setComment(String newComment)
{ ... }
String getComment()
{ ... }
void print()
{ ... }
...
}
public class DVD
{
private String title;
private String director;
private String comment;
DVD(String theTitle, String theDirector)
{
title = theTitle;
director = theDirector;
comment = " ";
}
void setComment(String newComment)
{ ... }
String getComment()
{ ... }
void print()
{ ... }
...
}
{
private String title;
private String director;
private String comment;
DVD(String theTitle, String theDirector)
{
title = theTitle;
director = theDirector;
comment = " ";
}
void setComment(String newComment)
{ ... }
String getComment()
{ ... }
void print()
{ ... }
...
}
class Database {
private ArrayList<CD> cds;
private ArrayList<DVD> dvds;
...
public void list()
{
for(CD cd : cds) {
cd.print();
System.out.println(); }
for(DVD dvd : dvds) {
dvd.print();
System.out.println(); }
}
}
private ArrayList<CD> cds;
private ArrayList<DVD> dvds;
...
public void list()
{
for(CD cd : cds) {
cd.print();
System.out.println(); }
for(DVD dvd : dvds) {
dvd.print();
System.out.println(); }
}
}
No hay comentarios:
Publicar un comentario