java certificacion
Post on 10-May-2015
420 Views
Preview:
DESCRIPTION
TRANSCRIPT
El lenguaje de programación JAVA
Dr. Hector G. Perez GonzalezM.C. Froylan Eloy Hernandez
Castro
Java
The green project
*7
Oak
Java
Java
J2Eava
PresentacionCliente
PresentacionServidor
Negocioservidor
Base de Datos
Empresa
Java
Una Aplicación Simple de JAVA
The TestGreeting.java Aplication//// Aplicación “Hola Mundo”//public class TestGreeting {
public static void main(String[ ] args) {Greeting hello = new Greeting( );hello.greet( );
}}
The Greeting.java Class
public class Greeting {public void greet ( ) {
system.out.println(“hi”);}
}
El lenguaje de programación JAVA
Parte 0 Diseño Orientado a Objetos
Diagrama de Clases
El Diagrama de Clases es el diagrama principal para el análisis y diseño
Un diagrama de clases presenta las clases del sistema con sus relaciones estructurales y de herencia
La definición de clase incluye definiciones para atributos y operaciones
El modelo de casos de uso aporta información para establecer las clases, objetos, atributos y operaciones
II. Breve Tour por UML
Ejemplos (Clase y Visibilidad)
Alumno
DNI : char[10]número_exp : intnombre : char[50]
alta()poner_nota(asignatura : char *, año : int, nota : float)matricular(cursos : asignatura, año : int)listar_expediente()
II. Breve Tour por UML
… Ejemplos (Asociación)
ProfesorDepartamento
10..1
director
1
dirige
0..1
II. Breve Tour por UML
… Ejemplos (Clase Asociación)
II. Breve Tour por UML
Empresa Empleado
1..** 1..**
trabajadoresempleador
Cargo
nombresueldo 0..1
1..*
superior
subordinado 1..*
0..1
… Ejemplos (Generalización)
II. Breve Tour por UML
Trabajador
Directivo Administrativo Obrero
{ disjunta, completa }
… Ejemplos
Prácticas 4-8
II. Breve Tour por UML
Avión militar Avión comercial
Avión de carga Avión de pasajeros
Motor Vendedor de billetes
Avión
1..4
1
1..4
1
Piloto
Reserva
n
1
n
1
Línea aérea
Vuelon1 n1
1..2
n
1..2
nn1 n1
1
n
1
n{ disjunta, completa }
{ disjunta, completa }
El lenguaje de programación JAVA
Parte 1 Fundamentos
Declarando Clases en JAVA
La Forma es la Siguiente:
<modifier>* class <class_name> {<attribute_declaration>*<constructor_declaration>*<method_declaration>*
}
Code 3 Example Class Declaration
public class vehicle {private double maxLoad;public void setMaxLoad(double value) {
maxLoad = value;}
}
Declarando Atributos
Forma:
<modifier>* <type> <name> [ = <initial_value>];
Ejemplo:
public class Foo {private int x;private float y = 10000.0F;private String name = "Bates Motel";
}
Declarando Métodos
Forma:
<modifier>* <return_type> <name> ( <argument>* ) {<statement>*
}
Ejemplo:
public class Dog { private int weight;public int getWeight( ) {
return weight;}public void setWeight(int newWeight) {
if( newWeight > 0 ) {weight = newWeight ;
}}
}
Accediendo a Miembros del objeto
Ejemplo:
public class TestDog {public static void main(String[ ] args) {
Dog d = new Dog();system.out.println("Dog d's weight is: "+ d.getWeight());d.setWeight(42);system.out.println("Dog d's weight is: "+ d.getWeight());d.setWeight(-42);system.out.println("Dog d's weight is: "+ d.getWeight());
} }
Salida:
Dog d's weight is 0 Dog d's weight is 42 Dog d's weight is -42
Información Oculta
Ejemplo:
public class MyDate {public int day;public int month;public int year;
}
Puede dar lugar a errores como:
d.day = 32; //dia invalido d.month = 2; d.day = 30; //posible pero incorrecto d.day = d.day + 1;
Declarando Constructores
Forma:
[ <modifier> ] <class_name> ( <argument>* ) {<statement>*
}
Ejemplo:
public class Dog {private int weight;
public Dog() {weight = 42;
} }
Recuerda, los constructores no tienen valores de retorno y no se heredan
La sentencia package
Forma:
package <top_pkg_name> [. <sub_pkg_name> ]* ;
Ejemplo:
package shipping.domain ;
// Class Vehicle of the 'domain' sub-package within // the 'shipping' application package. public class Vehicle {
... }
La Sentencia import
Forma:
import <pkg_name> [ .<sub_pkg_name> ] .<class_name> ;ó import <pkg_name> [ .<sub_pkg_name> ].* ;
Ejemplo:
package shipping.reports ;
import shipping.domain.* ; import java.util.List ; import java.io.* ;
public class VehicleCapacityReport {private Company companyForReport ;
... }
Certificación JAVA
Parte 2 Tipos de Datos y Paso de Parámetros
ComentariosExisten 3 tipos diferentes de comentarios:
// Comentario en una línea
/* * Comentarios en una * o mas lineas */
/** * Comentario de Documentación * Puede abarcar una o mas lineas * */
Nota: El formato de Documentación es para ser usado con La herramienta Javadoc, que genera documentación en HTML
Palabras Clave en JAVA
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Tipos de Datos básicos en JAVA
Tipos PrimitivosEl Lenguaje de Programación JAVA permite 8 tipos de datos primitivos, que pueden ser considerados en 4 categorías:• Lógicos – boolean• Textuales – char• Enteros – byte, short, int y long• De Punto Flotante – double y float
BoleanosEjemplo:
Bolean truth = true;Notas:
• Los valores true, false y null, se escriben con minusculas y no en mayusculas como en otros Lenguajes.
• No existen equivalencias entre enteros y boleanos, Cuando un valor boleano es requerido, solo se aceptan valores boleanos
Tipos de Datos Básicos en JAVA
CharEjemplos:
‘a’ La letra a‘\t’ Tabulacion‘\u????’ Carácter especifico de Unicode
StringEjemplos:
String greeting = “Good Morning !! \n”;String errorMessage = “Record not Found !”;String str1,str2;
Nota:A diferencia de C y C++, las cadenas no terminan con \0
Tipos de Datos Básicos en JAVA
Integrales – int, byte, short y longEjemplos:
2 Forma decimal para el dos077 El 0 al inicio indica un valor octal0xBAAC El 0x al inicio indica un valor hexadecimal2L La L al final indica un tipo de dato long
Punto Flotante – float y doubleEjemplos:
3.14 un tipo de dato double simple6.02E23 un tipo de dato double largo2.718F un tipo de dato flota simple123.4E+306D un tipo de dato double largo con la D redundante.
Datos Básicos en JAVA
Reservado de Memoria
my_birth ????
Ejemplo:MyDate my_birth;
MyDate my_birth = new MyDate(22 , 7 , 1964);
my_birth ????
day 22month 7year 1964
Paso por Valor
public class PassTest {
public static void changeInt(int value) {value=55;
}
public static void changeObjectRef(MyDate ref) {ref = new MyDate(1 , 1 , 2000);
}
public static void changeObjectAttr(MyDate ref) {ref.SetDay(4);
}
Paso por Valorpublic static void main(String args[]) {
MyDate date;int val;
val=11;
changeInt( val );System.out.println("Int value is: " + val);date = new MyDate(22,7,1964);ChangeObjectRef(date);System.out.println("MyDate: " + date);changeObjectAttr(date);System.out.println("MyDate: " + date);
}}
Salida:Int value is: 11MyDate: 22-7-1964MyDate: 4-7-1964
Ejemplos
public class ShirtTest {
public static void main(String args[]) {
Shirt myShirt;myShirt = new Shirt();
myShirt.displayShirtInformation();}
}
Ejemplos
public class ShirtTestTwo {
public static void main(String args[]) {
Shirt myShirt = new Shirt();Shirt yourShirt = new Shirt();
myShirt.displayShirtInformation();yourShirt.displayShirtInformation();
myShirt.colorCode = 'R';yourShirt.colorCode = 'G';
myShirt.displayShirtInformation();yourShirt.displayShirtInformation();
}}
Variable y Objeto son Referenciados
Variable y Objeto son Referenciados
Mas Ejemplos
public class Rectangulo extends Geometria { // definición de variables miembro de la clase
private static int numRectangulos = 0; protected double x1, y1, x2, y2; // constructores de la clase public Rectangulo(double p1x, double p1y, double p2x, double p2y) { x1 = p1x;
x2 = p2x;y1 = p1y;y2 = p2y;numRectangulos++;
} public Rectangulo() { this(0, 0, 1.0, 1.0); } // definición de métodos
public double perimetro() { return 2.0 * ((x1-x2)+(y1-y2)); }public double area() { return (x1-x2)*(y1-y2); }
} // fin de la clase Rectangulo
VariosOperador instanceofEl operador instanceof permite saber si un objeto pertenece a una determinada clase o no.Es un operador binario cuya forma general es:
objectName instanceof ClassNamey que devuelve true o false según el objeto pertenezca o no a la clase.
Variables miembro de clase (static)Una clase puede tener variables propias de la clase y no de cada objeto. A estas variables se les llama variables de clase o variables static.
VARIABLES FINALESUna variable de un tipo primitivo declarada como final no puede cambiar su valor a lo largo de la ejecución del programa. Puede ser considerada como una constante, y equivale a la palabra const de C/C++.
Permiso de Acceso en JAVA
Certificación JAVA
Parte 3 Clases, Métodos y Atributos
Elevadorpublic class Elevator {
public boolean doorOpen= false;public int currentFloor= 1;
public final int TOP_FLOOR = 5;public final int BOTTOM_FLOOR = 1;
public void openDoor() {System.out.println("Opening Door");doorOpen = true;System.out.println("Door is Open");
}
public void closeDoor() {System.out.println("Closing Door");doorOpen = false;System.out.println("Door is Closed");
}
public void goUp() {System.out.println("Going up one floor");currentFloor++;System.out.println("Floor: "+currentFloor);
}
Elevadorpublic void goDown() {System.out.println("Going Down one floor");currentFloor--;System.out.println("Floor: "+currentFloor);
}
public void setFloor(int desiredFloor) {while(currentFloor != desiredFloor) {
if(currentFloor < desiredFloor) {goUp();
}else {
goDown();}
}}
public int getFloor() {return currentFloor;
}
public boolean checkDoorStatus() {return doorOpen;
}}
Elevatorpublic class ElevatorTestTwo {
public static void main(String Args[]) {Elevator myElevator = new Elevator();
myElevator.openDoor();myElevator.closeDoor();myElevator.goUp();myElevator.goUp();myElevator.goUp();myElevator.openDoor();myElevator.closeDoor();myElevator.goDown();myElevator.openDoor();myElevator.closeDoor();myElevator.goDown();
int curFloor = myElevator.getFloor();System.out.println("Current Floor: "+curFloor);
myElevator.setFloor(curFloor+1);
myElevator.openDoor();}
}
Estaticos
Declarando Metodos Estaticos
Los metodos estaticos son declarados utilizando la palabra clave "static".Por ejemplo:
static Properties getProperties()
Invocando metodos Estaticos
Debido a que los metodos de clase o estaticos no son parte de cada instancia de la clase, No se debe de utilizar un objeto referencia para invocarlos, en su lugar se debe de utilizar el nombre de la clase.
Sintaxis:Classname.method();
Estaticos
Declarando variables Estaticas
Otro uso de la palabra clave static es para declarar variables de lasque solo puede haber una copia en momoria asociada a la clase, nouna copia por cada instancia de la clase.Ejemplo:
static doublesalesTax = 8.25;
Forma de acceso
De igual manera que los metodos, se debe de utilizar el nombre de la clase.Ejemplo:
Classname.variable;
SobreCarga
public class calculator {
public int sum(int numberOne, int numbreTwo) {System.out.println("Method One");return numberOne + numberTwo;
}
public float sum(float numberOne, float numbreTwo) {System.out.println("Method Two");return numberOne + numberTwo;
}
public float sum(int numberOne, float numbreTwo) {System.out.println("Method Three");return numberOne + numberTwo;
}}
SobreCarga
public class CalculatorTest {
public static void main(String Args[]) {Calculator myCalculator = new Calculator();
int totalOne = myCalculator.sum(2,3);System.out.println( totalOne );
float totalTwo = myCalculator.sum( 15.99F , 12.85F );System.out.println( totalTwo );
float totalThree = myCalculator.sum( 2 , 12.85F );System.out.println( totalThree );
}}
Elevador Encapsuladopublic class PrivateElevator2 {
private boolean doorOpen= false;private int currentFloor= 1;private int weight= 0;
private final int CAPACITY = 100;private final int TOP_FLOOR = 5;private final int BOTTOM_FLOOR = 1;
public void openDoor() {doorOpen = true;
}
public void closeDoor() {calculateCapacity();
if(weight<=CAPACITY) {doorOpen = false;
}else { System.out.println("The elevator has exceeded capacity"); System.out.println("Doors will Remain open until someone exits");
}}
private void calculateCapacity() {weight =(int) (Math.random() * 1500);System.out.println("The weight is: "+weight);
}
public void goUp() {if(!doorOpen) {
if(currentFloor<TOP_FLOOR) {currentFloor++;System.out.println(currentFloor);
}else {
System.out.println("Already on top Floor.");}
}else {
System.out.println("Doors Still Open");}
}
public void goDown() {if(!doorOpen) {
if(currentFloor>BOTTOM_FLOOR) {currentFloor--;System.out.println(currentFloor);
}else {
System.out.println("Already on Bottom Floor.");}
}else {
System.out.println("Doors Still Open");}
}
public void setFloor(int desiredFloor) { if((desiredFloor>=BOOTOM_FLOOR) && (desiredFloor<=TOP_FLOOR))
while(currentFloor != desiredFloor) {if(currentFloor < desiredFloor) {
goUp();}else {
goDown();}
} } else {
System.out.println("Invalid Floor"); }}
public int getFloor() {return currentFloor;
}
public boolean checkDoorStatus() {return doorOpen;
}}
Creando ArreglosSe pueden crear arreglos usando la palabra clave new.Por Ejemplo:
s=new char[26];
La linea anterior crea un arreglo de 26 caracteres,los elementos soninicializados con su valor por default (En este caso '\u0000')
Se debe de inicializar para que sea practico:
public char[ ] createArray() {char [ ]s;
s=new char[26];for(int i=0;i<26;i++) {
s[i]=(char)('A'+i);}return s;
}
Creando Arreglos de Referencias
Se pueden crear arreglos de Objetos
p=new Point[10];
Se crea un arreglo de 10 referencias de tipo Point,Sin embargo no se crean 10 objetos de tipo Point, Se tienen que crear por separado.
public Point[ ] createArray() {Point p[ ];
p= new Point[10];for(int i=0;i<10;i++) {
p[i]=new Point(i, i+1);}return p;
}
Podemos crearlos con valores iniciales:String[ ]names = {
"Georgiana","Jen","Simon"
};
que es equivalente a:
String[ ] names;names=new String[3];names[0]="Georgiana";names[0]="Jen";names[0]="Simon";
Se puede utilizar para cualquier objeto:
MyDate[ ] dates = {new MyDate(22, 7, 1964),new MyDate(1, 1, 2000),new MyDate(22, 12, 1964);
};
El manejo de arreglosMultidimensionales en JAVA es muy Particular,ya que son arreglos de arreglos, por ejemplo arreglos de dos dimensiones:
int [ ][ ] twoDim = new int [4][ ];twoDim[0]=new int[5];twoDim[1]=new int[5];
o tambien permite una forma mas conocida:
int [ ][ ] twoDim = new int [4][5];
Arreglos Multidimensionales
Limites del Arreglo
El numero de indices siempre inicia en cero.El numero de elementos en el arreglo es almacenado comoparte del arreglo en el campo length.Si se quiere acceder a elementos del arreglo fuera del rangouna excepcion es arrojada.
Ejemplo:public void printElements(int[ ] List) {
for(int i=0;i<List.length;i++) {System.out.println(list[i]);
}}
Version Mejorada del for para Arreglos
Ejemplo:
public void printElements(int[ ] list) {for( int element : list ) {
System.out.println(element);}
}
Esta mejora es exclusiva de la version 5.0 de JAVA
Modificando el Tamaño del Arreglo
Despues de que el arreglo es creado, no se puede modificar el tamañodel mismo, sin embargo es posible utilizar la misma referencia paraseñalar un nuevo arreglo.
Ejemplo:
int[ ] myArray = new int[6]; myArray =new int[10];
La primera referencia se pierde
Copiando Arreglos
JAVA provee un método especial en la clase System, este método es arraycopy()
Ejemplo:
int[ ] myArray = { 1, 2, 3, 4, 5, 6 };
int[ ] hold = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
System.arraycopy(myArray, 0, hold, 0, myArray.length );
Al terminar el arreglo hold contendra: 1,2,3,4,5,6,4,3,2,1
Nota: Este método solo copia referencias, no objetos.
Construyendo e Inicializando Objetos - Un breve Repaso
El proceso completo, para la creacion de objetos es el siguiente:
Primero se reserva la memoria para todo el objeto y a las variablesde instancia le son asignados sus valores por default, posteriormentelos constructores de mayor nivel son llamados y los siguientes pasosson ejecutados recursivamente segun sea el arbol de Herencia.
1.-Obtener los parametros del constructor
2.-Si existe un this(), llamar recursivamente, y luego saltar al paso 5
3.-Llamar recursivamente al super explicito o implicito (Ecepto para Object,ya que esta clase no tiene padres).
4.-Ejecutar los inicializadores de las variables de instancia explicitos
5.-Ejecutar el cuerpo del Constructor
Ejemplo:
public class Object { public Object() { }}
public class Employee extends Object {
private String name; private double salary = 15000.00; private Date birthDate;
public Employee(String n, Date DoB) {name=n;birthDate=DoB;
}
public Employee(String n) {this(n , null);
}}
public class Manager extends Employee { private String department;
public Manager(String n, String d) {super(n);department = d;
}}
Los pasos siguientes es la secuencia que se realizo al construirnew Manager("Joe Smith","sales");
-Inicializacion Basica -Se reservo memoria para el objeto Manager -Se inicializaron todas las variables de instancia con sus valores por default-LLamada al Constructor: Manager("Joe Smith","sales") -Se obtuvo los parametros: n="Joe Smith", d="Sales" -No hay llamada explicita a this -Se llama al Super(n) para Employee(String) -Obtiene parametros: n="Joe Smith" -Se llama a this(n,null) para Employee(String, Date) -Obtenemos parametros: n="Joe Smith", DoB=null -No hay llamada a this explicita -Llamada al super() para Object -No se necesita obtener parametros
-No hay llamada a this-No hay llamada a un Super (Object es la raiz)-No hay variables de inicializacion explicitas para Object-No hay cuerpo del Constructor
-Se inicializan las variables de Employee explicitas: salary=15000.00 -Se ejecuta el cuerpo: name="Joe Smith"; date=NULL; -Se saltan los pasos 3 y 4 -Se ejecuta el cuerpo: No hay demas cuerpo en Employee(String) -No hay inicializacion explicita para Manager -Se ejecuta el cuerpo: department="Sales"
Certificación JAVA
Parte 4 Clases Abstractas y Excepciones
El metodo equalspublic class My Date { private int day;
private int month;private int year;
public MyDate(int day,int month,int year) {this.day=day;this.month=month;this.year=year;
}
public boolean equals(Object o) { boolean result=false; if( (o!=null) && (o instanceof MyDate) ) { MyDate d= (MyDate) o; if( (day==d.day) && (month==d.month) && (year==d.year) )
{ result=true; } } return result;}
public int hashCode() { return (day ^ month ^ year);}
}
equals
class TestEquals {
public static void main(String []args) { MyDate date1 = new MyDate(14,3,1976);
MyDate date2 = new MyDate(14,3,1976);
if(date1==date2) { System.out.println("date1 is identical to date2");} else { System.out.println("date1 is not identical to date2");}
if(date1.equals(date2)) { System.out.println("date1 is equal to date2");} else { System.out.println("date1 is not equal to date2");}
equals -Continuación
System.out.println("set date2 = date1;");date2=date1;
if(date1==date2) { System.out.println("date1 is identical to date2");} else { System.out.println("date1 is not identical to date2");}
}}
Clases Wrapper
int pInt = 420;Integer wInt = new Integer(pInt);int p2=wInt.intValue();
int x=Integer.ValueOf(str).intvalue();
ó
int x=Integer.parseInt(str);
De forma automatica
int pInt = 420;Integer wInt = pInt;int p2=wInt;
Nota: Una vez que la clase wrapper se le asigna un valor, este ya no se puede modificar.
Inicializadores Estaticos
public class Count4 {public static int counter;static {
counter=Integer.getInteger("myApp.Count4.counter").intValue();}
}
public class TestStaticInit {public static void main(String []args) { System.out.println("counter ="+ Count4.counter);}
}
Nuevo Tipo Enumeradopackage cards.domain;public enum Suit {
SPADES,HEARTS,CLUBS,DIAMONDS
}
package cards.domain;
public class PlayingCard { private Suit suit; private int rank;
public PlayingCard(Suit suit,int rank) {this.suit=suit;this.rank=rank;
}
public Suit getSuit() {return suit;
}
Tipo Enumerado -Continuación
public String getSuitName() {String name="";switch( suit ) {
case SPADES: name="Spades"; break;case SPADES: name="Spades"; break;case SPADES: name="Spades"; break;case SPADES: name="Spades"; break;default:
}return name;
}}
Tipo Enumerado – Avanzado
package cards.domain;
public enum Suit {SPADES ("Spades"),HEARTS ("Hearts"),CLUBS ("Clubs"),DIAMONDS ("Diamonds");
private final String name;
private Suit(String name) {this.name=name;
}
public String getName() {return name;
}}
package cards.tests;
import cards.domain.PlayingCard;import cards.domain.Suit;
public class TestPlayingCard {
public static void main(String [ ]args) {
PlayingCard card1=new PlayingCard(Suit.SPADES,2);
System.out.println("card1 is the "+card1.getRank()+" of "+card1.getName()); }}
Tipo Enumerado – Avanzado
Clases Abstractas
public class ShippingMain { public static void main(String []args) {
Company c=new Company();
c.addVehicle(new Truck(10000.0));c.addVehicle(new Truck(15000.0));c.addVehicle(new RiverBarge(500000.0));c.addVehicle(new Truck(9500.0));c.addVehicle(new RiverBarge(750000.0));
FuelNeedsReport report=new FuelNeedsReport(c);
report.generateText(System.out); }}
Clases Abstractaspublic class FuelNeedsReport { private Company company;
public FuelNeedsReport(Company company) {this.company=company;
}
public void generateText(PrintStream output) {Vehicle v;double fuel;double total_fuel = 0.0 ;
for(int i=0;i<company.getFleetSize();i++) { v=company.getVehicle(i); fuel=v.calcTripDistance()/v.calcFuelEfficency();
output.println("Vehicle "+v.getName()+" needs "+fuel+" liters of fuel.");
total_fuel+=fuel;}output.println("Total fuel needs is "+total_fuel+"liters.");
}}
Clases Abstractas
public class abstract class Vehicle { public abstract double calcFuelEfficiency(); public abstract double calcTripDistance();}
Exceptions
public class AddArguments { public static void main(String []args) {
int sum=0;for(int i=0;i<args.length;i++) { sum+=Integer.parseInt(args[i]);}System.out.println("Sum = "+sum);
}}
Este codigo manda una excepcion si los argumentos del programa no son enteros.
La Sentencia try-catch
public class AddArguments2 { public static void main(String [ ]args) {
try { int sum=0; for(int i=0;i<args.length;i++) { sum+=Integer.parseInt(args[i]); } System.out.println("Sum = "+sum);} catch (NumberFormatException nfe) { System.err.println("One of the command-line arguments is not an
integer"); } }}
Manejo de Excepciones
public class AddArguments3 { public static void main(String [ ]args) {
int sum=0;for(int i=0;i<args.length;i++) { try { sum+=Integer.parseInt(args[i]); } catch (NumberFormatException nfe) { System.err.println("["+args[i]+"]is not an integer"
+"and will not be included in the sum."); }}System.out.println("Sum = "+sum);
}}
La Cláusula finally
try {startFaucet();waterLawn();
} catch (BrokenPipeException e) {logProblem(e);
} finally {stopFaucet();
}
Sobreescritura de Métodos y Excepciones
public class TestA {public void MethodA() throws IOException {
//Manejo de Codigo}
}
public class TestB1 extends TestA {public void MethodA() throws EOFException {
//Manejo de Codigo}
}
public class TestB2 extends TestA {public void MethodA() throws Exception {
//Manejo de Codigo}
}
Creando tus Propias Excepciones
public class ServerTimedOutException extends Exception { private int port;
public ServerTimedOutException (String message, int port) {super(message);this.port=port;
}
public int getPort() {return port;
}}
para lanzar tu propia excepcion throw new ServerTimedOutException("Could not connect",80);
Lanzando Excepciones Definidas por el usuario
public void connectMe(String serverName) throws ServerTimedOutException {
boolean succesful; int portToConnect=80;
succesful = open(serverName,portToConnect);
if(!succesful) {throw new ServerTimedOutException("Could not
connect",portToConnect); }}
Manejo de Excepciones definidas por el usuario
public void findServer() { try {
connectMe(defaultServer); } catch (ServerTimedOutException e) {
System.out.println("Server Timed out, Trying alternative");try { connectMe(alternativeServer);} catch (ServerTimedOutException e1) {
System.out.println("Error: "+e1.getMessage()+"connecting to port "+e1.getPort());
} }}
Certificación JAVA
Parte 5 Hilos (Threads)
Creación de un Hilo
public class ThreadTester { public static void main(String args[]) {
HelloRunner r=new HelloRunner();Thread t=new Thread(r);t.start();
}
class helloRunner implements Runnable { int i; public void run() {
i=0;while(true) { System.out.println("Hello " + i++); if(i==50) break;}
} }
Ciclo de vida de un Hilo
Deteniendo un hilo
class Runner implements Runnable { private boolean timeToQuit=false; public void run() {
while( !timeToQuit ) { // realiza trabajo hasta que le digamos que pare}
}
public void stopRunning() {timeToQuit=true;
} }
Deteniendo un hilo -Continuacion
public class threadController { private Runner r=new Runner(); private Thread t=new Thread(r);
public void startThread() {t.start();
}
public void stopThread() {r.stopRunning();
}}
Referencia a si mismo
public class NameRunner implements Runnable { public void run() {
while( true ) { // realiza trabajo sin parar}//Imprime el nombre del hilo actualSystem.out.println("Thread "+ Thread.currentThread().getName()+"
completed"); }
}
Otras formas de implementar Hilos
public class MyThread extends Thread { public void run() { while(true) {
//realiza varias acciones
try { sleep( 100 ); }catch( InterruptedException e ) { //sueño interrumpido }
} public static void main(String args[]) {
Thread t=new MyThread();t.start();
} }
Un Ejemplo Completo – Productor Consumidor
public class Producer implements Runnable { private SyncStack theStack; private int num; private static int counter=1;
public Producer(SyncStack s) { theStack=s; num=counter++; }
public void Run() {char c;
for(int i=0;i<200;i++) { c=(char)(Math.random()*26+'A'); theStack.push(c); System.out.println("Producer-"+num+": "+c); try { Thread.sleep((int)(Math.random()*300)); }catch ( InterruptedException e ) { //Se ignora }
} } }
Consumidor
public class Consumer implements Runnable { private SyncStack theStack; private int num; private static int counter=1;
public Consumer(SyncStack s) { theStack=s; num=counter++; }
public void Run() {char c;
for(int i=0;i<200;i++) { c=theStack.pop(); System.out.println("Consumer-"+num+": "+c); try { Thread.sleep((int)(Math.random()*300)); }catch ( InterruptedException e ) { //Se ignora }
} } }
El stack
import java.util.*
public class SyncStack { private List<Character> buffer=new ArrayList<Character>(400);
public synchronized char pop() {char c;while(buffer.size()==0) { try {
this.wait(); }catch( InterruptedException e ) {
//se ignora }
}c=buffer.remove(buffer.size()-1);return c;
}
public synchronized void push(char c) {this.notify();buffer.add(c);
} }
Prueba
public class SyncTest { public static void main(String args[]) {
SyncStack stack=new SyncStack();
Producer p1 = new Producer(stack);Thread prodT1 = new Thread(p1);prodT1.start();
Producer p2 = new Producer(stack);Thread prodT2 = new Thread(p2);prodT2.start();
consumer c1 = new Consumer(stack);Thread consT1 = new Thread(c1);consT1.start();
consumer c2 = new Consumer(stack);Thread consT2 = new Thread(c2);consT2.start();
}}
top related