Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Facultad de Informática
Grado en Ingeniería Informática, Grupo A
Tecnología de la Programación
Introducción a la Programación
Orientada a Objetos
Simon Pickin,
Alberto Díaz, Puri Arenas
variables de programa
Goto statement considered harmful
atributos
método
funciones miembro
propiedades
get set
Programación imperativa
encapsulación ocultación de información
la noción de ID de objeto
inculación dinámica
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B
Tecnología de la Programación
Introducción a Java
Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García
o
o
o
o
o
o
o
o
o
o
2-2
o
o
o
o
o
2-3
o
sin modificación alguna
o
2-4
sandbox
2-5
2-6
-7
§2 - 8
Java Standard Edition
o Java Runtime Environment
javac java
jdb javadoc
o
2-9
java.lang String
java.io java.nio
java.net
java.util
java.awt
javax.swing
2 - 10
o
o
2 - 11
package nombrePaquete;
o
o
2 - 12
o public static void main(String[] args)
o
.java
o
o public
o public
.class
o
2 - 13
.class .o .obj
o
.h
java.lang
import <nombrePaquete>.<nombreClase> import <nombrePaquete>.
interface
o
o CLASSPATH
o –classpath -cp java javac
2 - 14
o
o
o
o
o
2 - 15
HolaMundo.java
// Este es mi primer progama en Java
2 - 16
HolaMundo
o public
main
o public static
o
println
PrintStream java.io
out
static System
java.lang
o out
2 - 17
o main
main
2 - 18
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B
Tecnología de la Programación
Clases y objetos
Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García
3-2
o
o public
o protected:
o package private
o private:
o private
o protected
3-3
private int x = 2;
private String cadena = "setze jutges d'un jutjat";
private boolean fin = true;
this
public class A {
private int x;
private int y;
§3 - 5
final
o
static
o
public
o
3-6
o
o
o
o void
o
3-7
3-9
o
o
o Object
o
Object
3 - 10
o
o public:
o protected
o package-private
o private:
3 - 11
o static
sobrecarga de métodos
o
void
3 - 12
public class A {
private int x;
// constructor "package-private": poco habitual
// (aquí solo para mostrar que es posible)
A(){this.x=0;}
Inicializadores
De acceso
o get
o de tipo primitivo
o getters
Mutadores
set
setters
Computadores
3 - 14
public class Rational {
// attributos
private int num;
private int den;
// constructores
public Rational(int n, int d){
this.num = n;
this.den = d;
}
public Rational(){
this(0,1)
}
3 - 15
// métodos accesores
// métodos mutadores
3 - 16
// métodos computadores
3 - 17
}
3 - 18
nombreObjeto.nombreMetodo(valores-de-parámetros-separados-por-comas)
nombreObjeto
o
3 - 19
main
signature
o public static void main( String[] args )
o
Main
3 - 20
o public:
o package-private
o private protected
3 - 21
o
x
p p private
o getP() una copia del
objeto p
3 - 23
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B
Tecnología de la Programación
Igualdad y copias
Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García
o ==
o equals Object
==
4-2
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
}
4-3
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
}
4-4
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
}
4-5
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
public boolean equals(A a){
return (this.x == a.x && this.y == a.y);
}
}
4-6
public class A {
private int x; private int y;
public A(int x, int y){ this.x = x; this.y = y; }
public boolean equals(A x){
return (this.x == a.x && this.y == a.y);
}
}
4-7
4-8
public class Main {
4-9
4 - 10
public class Main {
4 - 11
equals() hashCode()
equals()
a.equals(b) b.equals(a)
a.equals(a)
a.equals(b) and b.equals(c) a.equals(c)
a == b a.equals(b)
hashCode() Object
o Hashtable HashMap
equals()
o hashCode()
4 - 12
hash table
4 - 13
clone()
clone()
o Object
4 - 14
shallow copy
int y = 6 int y = 6
int z = 4 int z = 4
b
a
4 - 15
deep copy
4 - 16
clone()
Object.clone()
clone()
o
Cloneable
clone()
4 - 17
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B
Tecnología de la Programación
Simon Pickin,
Alberto Díaz, Puri Arenas, Yolanda García
5-2
widening
5-3
5-4
5-5
5-6
5-7
5-8
5-9
5 - 10
5 - 11
5 - 12
5 - 13
5 - 14
5 - 15
5 - 16
breakpoint
5 - 17
5 - 18
5 - 19
5 - 20
En la declaración
En la asignación
En la declaración
En la asignación
5 - 21
" "
5 - 22
modificación del valor del parámetro
5 - 23
5 - 24
5 - 25
5 - 26
wrapper classes
5 - 27
wrapper classes
tipos genéricos
5 - 28
Boxing unboxing
Auto boxing
Unboxing
5 - 29
5 - 30
5 - 31
asociación
navegable
multiplicidad
rol
5 - 32
5 - 33
Tecnología de la programación
Apéndice
5A - 35
5A - 36
5A - 37
MAX
MAX
5A - 38
5A - 39
5A - 40
5A - 41
get
§5A - 42
java archive
bytecode
classpath
§5A - 43
java archive
§5A - 44
java archive
§5A - 45
java archive
§5A - 46
java archive
§5A - 47
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B
Tecnología de la Programación
La Herencia en la Programación
Orientada a Objetos
Simon Pickin
Alberto Díaz, Puri Arenas, Marco Antonio Gómez
§6 - 2
es-un
es-un
§6 - 3
public class
private long
private
public
public long
this
this
.... //
//
public void
this
this
§6 - 4
§6 – 5
public
§6 - 6
new
§6 - 7
§6 - 8
la fragilidad de la
clase base
§6 - 9
Object
§6 - 10
§6 - 11
error
§6 - 12
6 - 13
§6 - 14
§6 - 15
§6 - 16
obrescritura
§6 - 17
§6 - 18
§6 - 19
§6 - 20
§6 - 21
ocultados
oculta
§6 - 22
§6 - 23
§6 - 24
§6 - 25
§6 - 28
contravariante
covariante
§6 - 29
§6 - 30
§6 - 31
§6 - 32
covarianza
§6 - 33
contravariante en el tipo de
los parámetros
§6 - 34
§6 - 35
§6 - 36
1. Arrays covariantes
2. Arrays contravariantes
3. Arrays invariantes
§6 - 37
§6 - 38
cualquier
herencia de implementación
§6 - 39
Usos
§6 - 40
cualquier
§6 - 41
public class
private int
private int
public int
public int
§6 - 42
public class extends
public int
§6 - 43
setters
§6 - 44
public
package private
package
private:
protected:
package
§6 - 45
§6 - 46
métodos abstractos métodos virtuales
§6 - 47
§6 - 48
§6 - 49
protected int
protected int
public
§6 - 50
public class extends
private int
private int
public int
return
public void
§6 - 51
public int
return
public void
§6 - 52
Constant Interface Antipattern
getter setter
getter
protocolo de comportamiento
§6 - 53
§6 - 54
Desde Java 8, se puede omitir el modificador de método public
y se pueden omitir los modificadores de atributo public static final
§6 - 55
§6 - 56
§6 - 57
§6 - 58
§6 - 59
§6 - 60
package-private
§6 - 61
§6 - 62
§6 - 63
mixin
§6 - 64
§6 - 65
§6 - 66
Java 8: solo se necesita si las implementaciones estándares incluyen estado
§6 - 67
default
default
§6 - 68
§6 - 69
§6 - 70
§6 - 71
§6 - 72
§6 - 73
§6 - 74
§6 - 75
//
#include
using namespace
class
public
void
class
public
void
§6 - 76
int
§6 - 77
§6 - 78
#include
using namespace
class
public
void
int
class public
public
void
§6 - 79
class public
public
void
int
§6 - 80
dos métodos mostrar1
no compila
virtual
comportamiento no definido
§6 - 81
§6 - 82
§6 - 83
§6 - 84
Java Language Specification Interface Members
§6 - 85
§6 - 86
§6 - 87
tipo estático
tipo dinámico
§6 - 88
§6 - 89
§6 - 90
§6 - 91
§6 - 92
§6 - 93
§6 - 94
class
public void
public void
§6 - 95
§6 - 96
// tipo estático B, tipo dinámico C
// ¿error? ¿qué es lo que se imprime?
§6 - 97
§6 - 98
// tipo estático B, tipo dinámico C
// ¿error? ¿qué es lo que se imprime?
§6 - 99
§6 - 100
// tipo estático B, tipo dinámico C
// ¿error? ¿qué es lo que se imprime?
§6 - 101
§6 - 102
downcasting
cast, downcast
§6 - 103
downcasting
§6 - 104
§6 - 105
§6 - 106
§6 - 107
§6 - 108
§6 - 109
§6 - 110
§6 - 111
§6 - 112
§6 - 113
§6 - 114
§6 - 115
§6 - 116
class
public
virtual int return
int return
class public
public
int return
int return
int
int
return
§6 - 117
class
public
virtual void
class public
public
void
§6 - 118
new
new
dynamic_cast
dynamic_cast
§6 - 119
class
class public
public
new
delete
private
int
new
delete
return
§6 - 120
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo B
Tecnología de la programación
Apéndice
§6 - 122
Diseña y documenta para la herencia o bien prohíbela
§6 - 123
§6 - 124
§6 - 125
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática, Grupo en Inglés
Tecnología de la Programación
Tratamiento de excepciones
Simon Pickin,
Yolanda García, Alberto Díaz, Marco Antonio Gómez, Puri Arenas,
o
o
o
o
§7 - 2
public class Overflow {
1
2
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Overflow.main(Overflow.java:6)
§7 - 3
Fatal
o
o
o
Recoverable
o
int:
§7 - 4
o
o throwing
o
main
o main
§7 - 5
§7 - 6
Exception
Throwable
o
Error
o
o
Exception
o
o IOException ArithmeticException
o Exception RunTimeException checked exceptions”
IOException
NullPointerException unchecked exception”
§7 - 7
Exception
o java.lang
Throwable Exception RuntimeException
o java.io
EOFException FileNotFoundException
o
Throwable
o String getMessage()
null
o void printStackTrace()
call stack
§7 - 8
Run-Time
o
o
o
ArithmeticException
run-time
o
§7 - 9
o
o
catch
throws
§7 - 10
catch
m0
o m0
o m1 m0 catch
throws
o m1 m2
m1 catch throws
o catch
§7 - 11
try catch
try
try
catch
o catch
o catch try
try
o catch
try
catch
o catch (*)
undeclared checked exception: compiler error
§7 - 12 try
try catch
o
o
catch
try catch
try {
...
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
§7 - 13
try catch
a = 0
java.lang.ArithmeticException: / by zero at
EjemploExcep.main(EjemploExcep.java:6)
Exception in thread "main" Process Exit...
§7 - 14
try catch
a = 0
No dividas por 0 (java.lang.ArithmeticException: / by zero)
La ejecución sigue ...
§7 - 15
o
o
o
o
finally
o try catch
o try catch
finally
§7 - 16
try catch finally
§7 - 17
new throw
o
if (size == 0) {
throw new EmptyStackException();
}
o
o
o
main
§7 - 18
o
o Exception Exception
RunTimeException
o throws
o
o
§7 - 19
Exception
§7 - 20
MiExcepcion
§7 - 21
main
Lanzo mi excepción desde aquí.
La tengo! MiExcepcion: error malísimo...
... y sigo.
§7 - 22
catch(Exception e1) {
// do something with exception e1
throw e2; // e2 may or may not be the same exception as e1
}
o
o
SQLException
RunTimeException
§7 - 23
try-with-resources
§7 - 24
try-with-resources
try finally
o
o Respuesta finally
try
try-with-resources
o try
o java.lang.AutoCloseable
try-with-resources
o try
o try finally
try finally
getSuppressed
§7 - 25
try-with-resources
try-with-resources
private static void printFile() throws IOException {
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
§7 - 26
try-with-resources
try-with-resources
private static void printFile() throws IOException {
try( FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)
) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
}
§7 - 27
interface
throw
o
o
o
§7 - 28
Universidad Complutense de Madrid
Facultad de Informática
Grado en Ingeniería Informática
Tecnología de la Programación
Entrada/Salida en Java
Simon Pickin
o
o System.in
o System.out System.err
o
o
o stream
stream
stream
§8 - 2
java.io
o
InputStream OutputStream
o
Reader Writer
stream streams
o
charset
InputStreamReader OutputStreamWriter
o streams
o
o
o
o
o
o
o
o
o long int
o
§8 - 4
InputStream OutputStream
stream
o stream streams
streams
o finally
o try-with-resources
o
§8 - 5
https://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html
§8 - 6
// FileInputStream read() devuelve -1 si se llega a fin de fichero
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream inBytes = null;
FileOutputStream outBytes = null;
try {
inBytes = new FileInputStream("bytes_in.txt");
outBytes = new FileOutputStream("bytes_out.txt");
int c; // almacena el valor del byte en los últimos 8 bits
while ((c = inBytes.read()) != -1) { outBytes.write(c); }
} finally {
if (in != null) { inBytes.close(); }
if (out != null) { outBytes.close(); }
}
}
}
§8 - 7
http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
http://www.studytrails.com/java-io/classDiagram.jsp
https://docs.oracle.com/javase/8/docs/api/java/io/package-tree.html
§8 - 8
Reader Writer
Stream
o charset charset
charset
streams streams
o FileReader FileWriter FileInputStream FileOutputStream
o String
o
streams
§8 - 9
§8 - 10
PrintWriter
http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
http://www.studytrails.com/java-io/classDiagram.jsp
https://docs.oracle.com/javase/8/docs/api/java/io/package-tree.html
§8 - 11
o
o
o
§8 - 12
stream
o stream buffered stream
o Reader BufferedReader
o Writer BufferedWriter
o InputStream BufferedInputStream
o OutputStream BufferedOutputStream
o flush()
§8 - 13
http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
§8 - 14
public class CopyBytes { // se ejecuta más rápido que el ejemplo 1
public static void main(String[] args) throws IOException {
BufferedInputStream inBytes = null;
BufferedOutputStream outBytes = null;
try {
inBytes = new BufferedInputStream(
new FileInputStream("bytes_in.txt"));
outBytes = new BufferedOutputStream
new FileOutputStream("bytes_out.txt"));
int c; // almacena el valor del byte en los últimos 8 bits
while ((c = inBytes.read()) != -1) { outBytes.write(c); }
} finally {
if (in != null) { inBytes.close(); }
if (out != null) { outBytes.close(); }
}
}
}
§8 - 15
InputStreamReader OutputStreamWriter
o Streams
o stream charset
o charset
String charset
o
java.nio.charset.Charset
java.nio.charset.CharsetDecoder
§8 - 17
§8 - 18
public class CopyUTF8Lines { // compara con el ejemplo 4
public static void main(String[] args) throws IOException {
BufferedReader inChars = null;
PrintWriter outChars = null;
try {
inChars = new BufferedReader(
new InputStreamReader(
new FileInputStream("UTF8chars_in.txt"), "UTF-8"));
outChars = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("UTF8chars_out.txt"), "UTF-8"));
String l; // PrintWriter tiene el método println (incluye salto)
while ((l = inChars.readLine()) != null){ outChars.println(l); }
} finally {
if (inChars != null) { inChars.close(); }
if (outChars != null) { outChars.close(); }
}
}
}
§8 - 19
stream
o FileInputStream FileOutputStream FileReader FileWriter
o String
o java.io.File
o java.io.FileDescriptor
streams
o boolean
o
o
§8 - 20
o RandomAccessFile
stream cursor
o
o seek()
o getFilePointer() long
o String
o java.io.File
String
o "r" "rw" "rws" "rwd"
§8 - 21
§8 - 22
data stream byte stream
o boolean char byte short int long float double
String
o DataInputStream DataOutputStream
data stream byte stream
data stream
o EOFException
o
o stream
§8 - 23
http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
§8 - 24
// Utiliza try-with-resources de Java 7
public void dataStreamInOut() throws IOException {
try(DataOutputStream data_out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("data.bin")))){
data_out.writeInt(123);
data_out.writeFloat(123.45F);
data_out.writeLong(789);
}
try(DataInputStream data_in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("data.bin")))){
int anInt = data_in.readInt(); // anInt == 123
float aFloat = data_in.readFloat(); // aFloat == 123.45
long aLong = data_in.readLong(); // aLong == 789
int anotherInt = data_in.readInt(); // lanza EOFException
}
}
§8 - 25
o
Data streams
PrintStream
o
String
o Integer.toString(x) "" + x x
o String.format
String
o x = Integer.parseInt() x
o NumberFormatException
o System.getProperty("line.separator") System.lineSeparator()
§8 - 26
o
o BufferedWriter.newLine()
String
o
String
o
o
o Scanner InputMismatchException
§8 - 27
java.io.PrintWriter
o print() println()
toString
o format() Formatter
printf()
PrintWriter IOException
o checkError() setError() clearError()
PrintStream, PrintWriter
§8 - 28
PrintWriter
§8 - 29
PrintWriter
§8 - 30
java.util.Scanner
o
o float int boolean String
o
InputMismatchException
o IOException ioException() IOException
§8 - 31
§8 - 32
o
o
o
o Person
o
§8 - 33
object stream
o ObjectInputStream ObjectOutputStream
o Serializable
Serializable
NotSerializableException
o
o readObject() Object
o transient
§8 - 34
public class ObjectStreamExample { // Utiliza try-with-resources
public static class Person implements Serializable {
public String name = null; public int age = 0;
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
try(ObjectOutputStream objectsOut = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream("person.bin")))){
Person outPerson = new Person();
outPerson.name = "Noam Chomsky"; outPerson.age = 89;
out.writeObject(outPerson);
}
try(ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream("person.bin")))){
Person inPerson = (Person) in.readObject();
}
}
}
§8 - 35
o Serializable
transient
§8 - 36
o
serialVersionUID
o
o serialVersionUID
serialVersionUID
o
o serialVersionUID
§8 - 37
java.io
ByteArrayInputStream CharArrayReader
o
ByteArrayOutputStream CharArrayWriter
o
o toByteArray() toCharArray()
StringReader StringWriter
o String
SequenceInputStream
o
§8 - 38
java.io
PipedInputStream PipedOutputStream
PipedReader PipedWriter
o threads
o
PusbackInputStream PushbackReader
LineNumberReader StreamTokenizer
o
o Scanner split() StreamTokenizer
FilterInputStream FilterOutputStream
FilterReader FilterWriter
o
o
§8 - 39
http://tutorials.jenkov.com/java-io/overview.html
§8 - 40
o
§8 - 41
o
o
o
java.io
o java.nio
§8 - 42
java.io
o
java.nio
o
§8 - 43
§8 - 44
o non-blocking I/O
o
o asynchronous I/O
o
o CompletionHandler Future
java.util.concurrent
§8 - 45
java.nio
o
o
java.nio java.io
o java.nio
o
o
non-blocking mode
o java.io java.nio
o FileChannel
AsynchronousFileChannel
§8 - 46
java.nio
o java.nio
o
java.nio
o
§8 - 47
java.nio
o
o
o FileChannel
§8 - 48
o
o java.io.File
o java.nio.file
o
Old habits die hard
o
§8 - 49
java.io.File
File
o
o getParent()
File
o exists()
o isFile() isDirectory()
o mkdir() mkdirs()
o length()
o renameTo()
o createNewFile() delete()
o list() listFiles()
o canRead()
canWrite() canExecute()
§8 - 50
java.io.File
§8 - 51
java.io.File
§8 - 52
java.nio.file
o
java.io.File
o
o
§8 - 53
java.nio.file.Path
Path
o
o
"." ".."
o
Path
o
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
o
§8 - 54
java.nio.file.Paths
Paths.get()
o Path
File
o String URI
varargs
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs
String
String
§8 - 55
java.nio.file.Files
o
o Files Path
o Files glob
§8 - 56
java.nio.file
Programming Technology
Appendix
java.io.File java.nio.file
java.nio.file.Path java.io.File
o
o java.nio.File.Path.toFile()
java.io.File java.nio.files
o https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
§8 - 59
\n
o
o
o newline() better!