Está en la página 1de 12

Programacin Orientada a Objetos

Interfaces, Contenedores y Casting

Angela C. Carrillo Ramos

Interface
Define un tipo con un contrato abstracto Una interface puede heredar de otras interfaces interface Y extends Z{ } // La clase que implemente Y debe implementar los mtodos de Y y de Z

Interface
Interface nomInterface{ nomInterface{ //firmas de mtodos y constantes } class nomClase implements nomInterface{ }

Interface
x = new nomInterface(); nomInterface x;
ERROR!!!

No es una instancia. Vlido!!!

x= new nomClase();

nomClase implementa nomInterface. Vlido!!!

Ejemplo
Interface Iterator{} Class Vector implements Iterator{} x = new Iterator(); Iterator x; x= new Vector(); // Pueden invocarse los Vector(); mtodos cuyas firmas estn descritas en Iterator. Iterator. No mtodos propios y definidos nicamente en Vector. Vector. //Error!!!

Colecciones
Tambin llamadas Contenedores Permiten almacenar y organizar objetos de forma til para un acceso eficiente. eficiente. Almacenan objetos de tipo Object Paquete: java. Paquete: java.util Son interfaces que heredan de la interface Collection

Contenedores
Collection: Collection: add, remove, size, iterator Set: Set: Contenedor sin elementos repetidos SortedSet: SortedSet: Es un Set cuyos elementos estn ordenados List: List: Coleccin cuyos elementos permanecen en un orden particular

Contenedores
Iterator: Iterator: Interface que devuelve elementos de una coleccin, de uno en uno
public boolean hasNext() public Object next() public void remove

Contenedores
public void eliminaCadenasLargas (Collection col, int longMax){ Iterator it = col.iterator(); while (it.hasNext()){ String cad = (String) it.next(); if (cad.length() > longMax) it.remove(); }

Contenedores
ListIterator
Extiende Iterator con mtodos como hasPrevious y previous ListIterator it = list.listIterator(list.size()); while (it.hasPrevious()){ Object obj = it.previous(); // utilizar el objeto }

Contenedores
Interface List
Extiende Collection Va de la posicin 0 a la list.size Al adicionar un elemento, queda al final de la lista Si se elimina un elemento, se comprime la lista

Contenedores
Interface List
public boolean get (int indice) public boolean set (int ind, Object elem) public boolean add (int ind, Object elem) public boolean remove (int indice) public int indexOf (Object elem) public int lastIndexOf (Object elem) public List subList(int min, int max) public ListIterator listIterator(int indice) public ListIterator listIterator()

Contenedores
ArrayList
Lista que almacena los elementos en un arreglo public ArrayList() public ArrayList(int capacidadInicial) public ArrayList(Collection col) public void trimToSize() public void ensureCapacity (int capacidadMin)

Contenedores
Vector
public Vector (int capIni, int incremento) public Vector (int capIni) public Vector () public Vector(Collection col) public final void addElement(Object elem) public final void insertElementAt(Object elem, int indice) public final void setElementAt (Object elem, int indice)

Contenedores
Vector
public final void removeElementAt (int indice) public final boolean removeElement (Object elem) public final void removeAllElements() public final Object elementAt(int indice) public final int indexOf(Object elem, int indice)

Contenedores
Vector
public final int lastIndexOf (Object elem, int index) public final Object firstElement() public final Object lastElement() public final int capacity()

Cmo almacenar y recuperar un elemento?


Clase obj1, obj2=new Clase(); Vector v = new Vector(); Para almacenar:
v.addElement(objeto);

Para recuperar:
obj1= (Clase) v.elementAt(pos);

Para saber de qu tipo es:


if (obj1 instanceOf Clase) If (v.elementAt(pos) instanceOf Clase)

Templates (Plantillas)
Mecanismo que permite definir clases que son parametrizadas por tipos, lo que hace estas clases polimrficas. polimrficas. Un template de Lista permite generar cualquier lista, mientras que una Lista de lista, Object es una lista de cualquier tipo de objetos. objetos. Con los templates no hay prdida de tipos

Templates (Plantillas)
Stack stack=new Stack(); stack.push(la casa de la loma"); ... Iterator it=stack.iterator(); while (it.hasNext())
System.out.println(((String)it.next()).substring(9)); System.out.println(((String)it.next()).substring(9));

Templates (Plantillas)
Stack<String> Stack<String> stack=new Stack<String>(); Stack<String>(); stack.push(la casa de la loma"); ... Iterator<String> Iterator<String> it=stack.iterator(); while (it.hasNext())
System.out.println(it.next().substring(9));

10

Templates (Plantillas)
class Sorter<Object key1,String key2> { Sorter<Object key1,String ... } Sorter<Object,Object> Sorter<Object,Object> // ilegal, Object no hereda de String Sorter<Object,String> Sorter<Object,String> // legal Sorter<String,String> Sorter<String,String> // legal, String hereda de Object Sorter<Integer,Integer> Sorter<Integer,Integer> // ilegal, Integer no hereda de
String

Sorter<int,String> Sorter<int,String> // ilegal, int es un tipo primitivo y no


hereda de Object

Templates (Plantillas)
type
Para indicar que el parmetro puede ser de cualquier tipo primitivo o de una clase Los nicos operadores vlidos son la asignacin y la igualdad. igualdad.

number
El parmetro puede ser de tipo : byte, char, double, float, int, long, short. short. Les operaciones posibles son la asignacin, suma, resta, multiplicacin, etc. etc.

11

Templates (Plantillas)
class Sum<number Value> { Sum<number abstract Value f(Value value); Value sum(Value debut,Value fin) { Value res=0; for(Value i=debut;i<=fin;i+=1) res+=f(i); return res; } }

12

También podría gustarte