2. Agenda
• Características de Java
• JDK
• Programación Orientada a Objetos
• Conceptos básicos
• Estatutos de Control
• Objetos y Clases en Java
• Ejercicios
3. Definición de Java (Sun Microsystems)
The Java programming language is a high-level
language that can be characterized by all of the following buzzwords:
•Simple and familiar
•Architecture neutral
•Object oriented
•Portable
•Distributed
•High performance
•Interpreted
•Multithreaded
•Robust
•Dynamic
•Secure
4. Caracteristicas de Java
• Familiar:
• Estrucutra parecida a lenguajes como C++
• Simple:
• Eliminaron caracteristicas inecesarias del
lenguaje C++ y no eran necesarias para aplicar
orientación a objetos (Se eliminó: typedefs, define,
estructuras y uniones, enumeraciones, funciones,
herencia multiple, goto, apuntadores, ajuste
automático valores primitivos.
5. Caracteristicas de Java
• Orientado a Objetos
• Encapsulación
• Polimorfismo
• Herencia
• Construcción Dinamica
7. Caracteristicas de Java
• Arquitectura neutral, portable
ComputadoraComputadora
Sistema OperativoSistema Operativo
Máquina Virtual (JVM)Máquina Virtual (JVM)
Byte-CodesByte-Codes
8. Caracteristicas de Java
• Dinámico
• Independencia entre clases. (link)
• Clases se cargan conforme se van requiriendo
• Multi Hilos (Threads)
• Sincronización
• Threads Seguros
• Rendimiento (Performance)
• Just In Time (JIT) compiler
11. JDK
• Bajar la última versión del JDK del “site”
de SUN (JDK 1.4.2)
• www.javasoft.com
• Instalar el JDK en la máquina
• Bajar la documentación
• Instalar la documentación
• Comenzar a programar en Java
12. Instalación del JDK
• Ejecutar el instalador (j2sdk-1_4_2_06-
windows-i586-p.exe)
• Modificar la variable de entorno path
(raizjdkbin)
• Ej: path=%path%;c:j2sdk1.4.2_06bin
• Modificar la variable de entorno CLASSPATH
• Ej: CLASSPATH=%CLASSPATH%;.
16. Programación Orientada a
Objetos
• Es una filosofía para el desarrollo de
sistemas basado en el modelado del
mundo real a través de la identificación de
objetos
• Surgió inicialmente como un enfoque para
la programación pero se ha extendido a
todo el ciclo de desarrollo de sistemas
17. Objeto
• Un elemento con estado,
comportamiento.
•Estado (lo que se sabe del objeto)
–Nombre, color, raza, contento
•Comportamiento (lo que puede hacer)
–Ladrando, durmiendo, corriendo
•Estado
–Número de llantas, color, marca, modelo
•Comportamiento
–Acelerando, frenando, Reparando.
19. Objeto (Software)
• Estado
– Representado por sus Variables
• Comportamiento
– Modificado por sus Métodos
Los objetos en programación representan
objetos reales y objetos abstractos (conceptos),
ej. Eventos
22. Encapsulación
- Permite ocultar los detalles
de la implementacion de un objeto
- El usuario solo tiene acceso a la Interfaz
API pública
Application Program Interface
23. Encapsulación
• Modularidad
– Independencia entre objetos
• Transparencia
– Publica una interfaz publica
– Puede cambiar la implementación sin afectar su
utilización
A veces se hacen públicas las variables
y se esconden algunos métodos por
razones de eficiencia
24. Mensajes
• Permiten la interacción entre objetos
• Mandar a ejecutar un método
MensajeMensaje
Acelera, frena, etc.
25. Parámetros
• A veces los métodos necesitan más
información para realizar una acción
• Esta información adicional se pasa en
forma de parámetros
enciende
enciende (%)
26. Mensajes
• Expresan el comportamiento de un objeto,
cambiando el estado de éste
• Ocultan la necesidad de exponer las
variables
• Los objetos pueden estar en procesos y/o
máquinas diferentes
27. Mensajes
• Objeto destino
• Nombre del método a
ejecutar
• Parámetros necesarios
focoSala.enciende(porcentaje)focoSala.enciende(porcentaje)
28. Clases
• Prototipo de objetos
• Definen las variables y métodos
comunes para todos los objetos
29. Clases y Objetos
• Los objetos son ejemplares (instancias) de
clases
• Los objetos de una clase comparten el
comportamiento (métodos)
• Cada objeto tiene su propio estado (variables)
30. Variables y Métodos de Clase
• De ejemplar (instancia)
– Se crea una copia particular de las variables y se
tiene acceso a los métodos
• De clase
– Todos los objetos de una clase comparten la
misma copia
– No se necesita crear un objeto para el acceso a
variables y métodos
– Si un objeto cambia una variable de clase, esa
variable se cambia para todos los objetos de la
clase
31. Variables y Métodos de Clase
• Ejemplo
Clase Perro
Objeto Perro
Fido
Objeto Perro
cuco
32. Abstracción
• La abstracción se refiere a quitar las
propiedades y acciones de un objeto que
no son necesarias para el sistema.
33. Herencia
• Especialización de una clase
• Subclases se definen con base en
Superclases
• La subclase hereda las variables y
métodos de la superclase
• La subclase define sus propias variables
y métodos los cuales se agregan a los de
la superclase
35. Herencia
• Esquema jerárquico
• Reutilización de código
• Una super clase puede guardar una
referencia a una subclase, Por ejemplo:
• Una televisión puede almacenar una instancia
de una televisión a color
Notes de l'éditeur
Simple and familiar: Muchos de los programadores estaban familiarizados con C++,
Another major design goal is that Java look familiar to a majority of programmers in the personal computer and workstation arenas, where a large fraction of system programmers and application programmers are familiar with C and C++. Thus, Java "looks like" C++. Programmers familiar with C, Objective C, C++, Eiffel, Ada, and related languages should find their Java language learning curve quite short--on the order of a couple of weeks. Simplicity is one of Java's overriding design goals. Simplicity and removal of many "features" of dubious worth from its C and C++ ancestors keep Java relatively small and reduce the programmer's burden in producing reliable applications. To this end, Java design team examined many aspects of the "modern" C and C++ languages 1 to determine features that could be eliminated in the context of modern object-oriented programming. Java has no structures or unions as complex data types. You don't need structures and unions when you have classes; you can achieve the same effect simply by declaring a class with the appropriate instance variables. The code fragment below declares a class called Point . Java has no enum types. You can obtain something similar to enum by declaring a class whose only raison d'etre is to hold constants. You could use this feature something like this: class Direction extends Object { public static final int North = 1; public static final int South = 2; public static final int East = 3; public static final int West = 4; } Java has no goto statement 1 . Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements. Most studies agree that pointers are one of the primary features that enable programmers to inject bugs into their code. Given that structures are gone, and arrays and strings are objects, the need for pointers to these constructs goes away. Thus, Java has no pointer data types
Dynamic binding --objects could come from anywhere, possibly across the network. You need to be able to send messages to objects without having to know their specific type at the time you write your code. Dynamic binding provides maximum flexibility while a program is executing
The Java compiler doesn't generate "machine code" in the sense of native hardware instructions--rather, it generates bytecodes : a high-level, machine-independent code for a hypothetical machine that is implemented by the Java interpreter and run-time system dynamically translate into native machine code if required by performance demands. C and C++ both suffer from the defect of designating many fundamental data types as "implementation dependent".
Native code is code that after you compile it, the compiled code runs on a specific hardware platform. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.
This problem arises as a side effect of the way that C++ is usually implemented. Any time you add a new method or a new instance variable to a class, any and all classes that reference that class will require a recompilation, or they'll break. Keeping track of the dependencies between class definitions and their clients has proved to be a fruitful source of programming error in C++, even with the help of "make"-like utilities. The fragile superclass issue is sometimes also referred to as the "constant recompilation problem Built-in support for threads provides Java programmers with a powerful tool to improve interactive performance of graphical applications. If your application needs to run animations and play music while scrolling the page and downloading a text file from a server, multithreading is the way to obtain fast, lightweight concurrency within a single process space. Threads are sometimes also called lightweight processes or execution contexts.
Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. You can give your bicycle to someone else, and it will still work. Information hiding: An object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it. You don't need to understand the gear mechanism on your bike to use it.
A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior