Академический Документы
Профессиональный Документы
Культура Документы
Objetos en Java
Unidad 3
Herencia y Polimorfismo
Temario
Herencia
Reescritura de mtodos
Polimorfismo
Clases abstractas
Interfaces
2
Herencia
In object-oriented programming (OOP), Inheritance is a way to
compartmentalize and reuse code by creating collections of
attributes and behaviors called objects which can be based on
previously created objects. In classical inheritance where
objects are defined by classes, classes can inherit other classes.
The new classes, known as Sub-classes (or derived classes),
inherit attributes and behavior of the pre-existing classes, which
are referred to as Super-classes (or ancestor classes). The
inheritance relationship of sub- and superclasses gives rise to a
hierarchy. In Prototype-based programming objects can be
defined directly from other objects without the need to define
any classes.
The inheritance concept was invented in 1967 for Simula.
Wikipedia
3
Herencia en Java
Todas las clases son descendientes de la clase Object
La clusula extends especifica el ancestro inmediato
de la clase
Una subclase o clase derivada hereda todos los
campos y mtodos de la superclase o clase base
Java soporta herencia simple (slo una clase base)
ancestro
superclase
clase base
"hereda de"
"extiende"
"is a"
descendientes
subclases
clases derivadas
4
Ejemplo
class Figura {
int x, y;
public void print() { ... }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; } La clase Circulo es derivada de la
} clase base Figura
class App {
void f() {
La clase Circulo hereda mtodos
Rectangulo r = new Rectangulo();
setX y setY de clase base Figura
r.setX(10); r.setY(20);
r.setAncho(100); r.setLargo(300);
}
} 5
Encapsulamiento
Una clase derivada tiene acceso a los
miembros public y protected de una clase
base, aunque pertenezcan a paquetes
diferentes
6
Polimorfismo
Polymorphism, in the context of object-oriented
programming, is the ability of one type, A, to appear
as and be used like another type, B. The purpose of
polymorphism is to implement a style of
programming called message-passing in the
literature, in which objects of various types define a
common interface of operations for users.
In strongly typed languages, polymorphism usually
means that type A somehow derives from type B, or
type C implements an interface that represents type
B. In weakly typed languages types are implicitly
polymorphic.
Wikipedia
7
Polimorfismo
Circulo circulo;
circulo = new Circulo();
Figura figura; circulo
figura = circulo;
figura
8
Polimorfismo
Java permite asignar un objeto a una
variable declarada con un tipo de datos
ancestro
void metodo1(Figura f) {
f.print();
...
}
void metodo2() {
metodo1(new Circulo());
}
9
Reescritura de Mtodos
Method overriding, in object oriented programming, is a
language feature that allows a subclass or child class to provide
a specific implementation of a method that is already provided
by one of its superclasses or parent classes. The implementation
in the subclass overrides (replaces) the implementation in the
superclass by providing a method that has same name, same
parameters or signature, and same return type as the method in
the parent class.The version of a method that is executed will
be determined by the object that is used to invoke it. If an
object of a parent class is used to invoke the method, then the
version in the parent class will be executed. If an object of the
subclass is used to invoke the method, then the version in the
child class will be executed.
Wikipedia
10
Reescritura de Mtodos
public class DTE {
...
public void validar() {
...
}
}
11
Dynamic Binding
Al invocar un mtodo no static, el tipo real
del objeto sobre el que se invoca el mtodo
y no el tipo de la referencia es utilizado
para determinar qu versin del mtodo
invocar
El tipo del objeto sobre el que se invoca el
mtodo se obtiene en tiempo de ejecucin,
por eso esta funcionalidad recibe el nombre
de dynamic binding, o late binding
void procesarDTE(DTE dte) {
dte.validar();
Dynamic binding: invoca a
... Factura.validar() si dte es una
} referencia a una Factura
12
Compatibilidad de Tipos
class DTE {
DTE(Empresa emisor, int folio) { ... }
...
}
16
Ejemplo: Diseo con Polimorfismo
18
Clases Abstractas
Una clase abstracta no puede ser instanciada
Puede contener mtodos abstractos, a ser implementados en
subclases
Puede contener mtodos concretos
20
Interfaces
In object-oriented languages the term interface is
often used to define an abstract type that contains
no data, but exposes behaviors defined as methods.
A class having all the methods corresponding to that
interface is said to implement that interface
(furthermore a class can implement multiple
interfaces, and hence can be of different types at the
same time).
An interface is hence a type definition; anywhere an
object can be exchanged (in a function or method
call) the type of the object to be exchanged can be
defined in terms of an interface instead of a specific
class. This allows later code to use the same function
exchanging different object types; hence such code
turns out to be more generic and reusable.
Wikipedia
21
Interfaces
An interface is a kind of classifier that represents a
declaration of a set of coherent public features and
obligations. An interface specifies a contract; any
instance of a classifier that realizes the interface must
fulfill that contract.
Since interfaces are declarations, they are not
instantiable. Instead, an interface specification is
implemented by an instance of an instantiable
classifier, which means that the instantiable classifier
presents a public facade that conforms to the
interface specification. Note that a given classifier
may implement more than one interface and that an
interface may be implemented by a number of
different classifiers.
UML Specification 2.0
22
Interfaces
Una interfaz (interface) es una coleccin de mtodos
abstractos y constantes
Una interfaz no puede ser instanciada
Una clase que implementa una interfaz debe
implementar los mtodos declarados en ella
Una clase puede implementar mltiples interfaces
Una interfaz define un tipo de datos que se puede
utilizar en la declaracin de variables
Una variable declarada mediante una interfaz puede
referenciar un objeto de alguna clase que
implemente la interfaz
Java soporta herencia mltiple de interfaces
23
Definiendo una Interfaz
interface Printable {
int PORTRAIT = 0;
int LANDSCAPE = 1;
void print(int orientacion);
}
25
Usando una Interfaz
Capa genrica
class ColaImpresion {
static void creaJob(Printable p) {
p.print(Printable.PORTRAIT);
}
}
Capa cliente
ColaImpresion.creaJob(new Empleado());
ColaImpresion.creaJob(new Rectangulo());
Libro libro = new Libro();
ColaImpresion.creaJob(libro);
26
Resumen
Herencia es un concepto de OOP mediante el
cual una clase adquiere las propiedades y los
mtodos de otra
Una variable de un tipo de datos ancestro
puede ser utilizada para referenciar una
instancia de una clase descendiente
Al invocar sobre un objeto un mtodo de
instancia que ha sido redefinido en subclases,
la mquina virtual invoca el mtodo definido
en la clase real del objeto, obtenida en
tiempo de ejecucin
27
Resumen
Una clase abstracta (abstract) puede
contener mtodos abstractos
Una interfaz (interface) es una coleccin de
mtodos abstractos y constantes
Las clases abstractas y las interfaces no
pueden ser instanciadas
Una clase puede extender a una clase, e
implementar un nmero ilimitado de
interfaces
Si una clase define o hereda mtodos
abstractos, debe ser declarada abstracta
28