Top Banner
PCG SG Campus Sun Certified Java Programmer 6.0 [email protected] Sun Educación
63

Section5 scjp6.0

May 22, 2015

Download

Education

Daniel Martinez

Java
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Section5 scjp6.0

PCG SG CampusSun Certified Java Programmer [email protected]

Sun Educación

Page 2: Section5 scjp6.0

Descripción del Examen

Page 3: Section5 scjp6.0

3

Sun Certified Java Programmer  6.0 

Requisitos previos: 6 – 12 meses experiencia

Tipo de Examen: Opción Múltiple, y respuesta corta

Número de preguntas:  60

Porcentaje mínimo: 58.33 % (35 / 60 preguntas)

Tiempo Limite: 180 minutos

Lenguajes disponibles: Ingles / Español

Page 4: Section5 scjp6.0

4

Sun Certified Java Programmer  6.0 

Centro Prometric

En equipo PC

Solo papel, lápiz

Encuesta Inicial

Información para  estadísticas

Costo del voucher: 300 USD por intento ( PCG retries número ilimitados)

El examen contiene 7 secciones como objetivos

Page 5: Section5 scjp6.0

Contenido del Examen

Page 6: Section5 scjp6.0

6

Sun Certified Java Programmer  6.0  Section 1: Declarations, Initialization and Scoping

Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.

Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Page 7: Section5 scjp6.0

7

Descripción de Secciones SCJP 6.0 Section 1: Declarations, Initialization and Scoping  (Continuación)

Develop code that declares both static and non­static methods, and ­ if appropriate ­ use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable­length argument list.

Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.

Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non­nested class listing, write code to instantiate the class.

Page 8: Section5 scjp6.0

8

Descripción de Secciones SCJP 6.0 Section 2: Flow Control

Develop code that implements an if or switch statement; and identify legal argument types for these statements.

 Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for­each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.

 Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.

 Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.

Page 9: Section5 scjp6.0

9

Descripción de Secciones SCJP 6.0 Section 2: Flow Control (Continuación)

Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error

Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.

Page 10: Section5 scjp6.0

10

Descripción de Secciones SCJP 6.0 Section 3: API Contents

Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.

Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter.

Develop code that serializes and/or de­serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.

Page 11: Section5 scjp6.0

11

Descripción de Secciones SCJP 6.0 Section 3: API Contents (Continuación 1)

Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.

Page 12: Section5 scjp6.0

12

Descripción de Secciones SCJP 6.0 Section 3: API Contents (Continuación 2)

Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.

Page 13: Section5 scjp6.0

13

Descripción de Secciones SCJP 6.0 Section 4: Concurrency

Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.

Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.

Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.

Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.

Page 14: Section5 scjp6.0

14

Descripción de Secciones SCJP 6.0 Section 5: OO Concepts

Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.

Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.

Page 15: Section5 scjp6.0

15

Descripción de Secciones SCJP 6.0 Section 5: OO Concepts (Continuación)

Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, overridden, or overloaded constructors.

Develop code that implements "is­a" and/or "has­a" relationships.

Page 16: Section5 scjp6.0

16

Descripción de Secciones SCJP 6.0 Section 6: Collections / Generics

Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.

Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non­generic Collections API. 

Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.

Page 17: Section5 scjp6.0

17

Descripción de Secciones SCJP 6.0 Section 6: Collections / Generics (Continuación)

Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.

Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.

Page 18: Section5 scjp6.0

18

 Section 7: Fundamentals

Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.

Given an example of a class and a command­line, determine the expected runtime behavior.

Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.

Descripción de Secciones SCJP 6.0

Page 19: Section5 scjp6.0

19

 Section 7: Fundamentals (Continuación 1)

Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.

Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, ­=), arithmetic operators (limited to: +, ­, *, /, %, ++, ­­), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

Descripción de Secciones SCJP 6.0

Page 20: Section5 scjp6.0

20

 Section 7: Fundamentals (Continuación 2)

Given the fully­qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.

Descripción de Secciones SCJP 6.0

Page 21: Section5 scjp6.0

21

Modificadores en JavaRepaso

Modifiers Top Class Inner Class Interface Method Constructorprivate NO SI NO NO SI SI SI SI NOdefault SI SI SI SI SI SI SI SI NOprotected NO SI NO NO SI SI SI SI NOpublic SI SI SI SI SI SI SI SI NOstatic NO SI NO NO SI SI NO SI NOfinal SI SI NO NO NO SI NO SI SIabstract SI SI SI NO NO SI NO NO NOtransient NO NO NO NO NO NO NO SI NOvolatile NO NO NO NO NO NO NO SI NO

Top Enums

Instance Enum

Instance Variable

Local Variable

Page 22: Section5 scjp6.0

22

Declaración y control de accesoModificadores y declaración de clases.

Reglas básicas

Solo puede existir una clase “public” por archivo fuente.

El nombre del archivo deberá de coincidir con el nombre de la clase publica.

La sentencia “package” (si la hay) deberá colocarse en la primera línea.

Si existen instrucciones “import” estas deberán de situarse entre la instrucción “package” y la declaración de clase.

Page 23: Section5 scjp6.0

23

Sintaxis en ClasesRegla:

[ access modifier ] [modifier ]* class NameClass{

}

Ejemplos:

public abstract class Person{}

strictfp abstract class TaxesType{}

public class Vehicle{}

class public WrongExample{}        //Error de Compilación

Page 24: Section5 scjp6.0

24

Sintaxis VariablesVariables de Instancia:

[ access modifier ] [modifier ]*  type nameVariable [ = value] ;

Ejemplos:

public class Person{

String firstName ;

int age = 0;

public static final int idPerson;

//...

}

Page 25: Section5 scjp6.0

25

Sintaxis VariablesVariables Locales:

[modifier final] type nameVariable [ = value];

Ejemplos:

public void method(){

int a = 10;

final double interestRate = 0.05 ;

private int  c = 100;          //Error de Compilación

}

Page 26: Section5 scjp6.0

26

Sintaxis MétodosMétodos

[access modifier] [modifier]*  returnType 

            nameMethod( [ arguments]*){  }

Ejemplos:

public void methodA(int a, float f){      }

public final  int methodB(){ return 100;}

public static void main(String args[]){     }

public native void methodC();

public abstract void methodD();

Page 27: Section5 scjp6.0

Section 5: OO Concepts

Page 28: Section5 scjp6.0

28

SCJP: Section 5 Section 5: OO Concepts

Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.

Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.

Page 29: Section5 scjp6.0

29

SCJP: Section 5 Section 5: OO Concepts (Continuación)

Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, overridden, or overloaded constructors.

Develop code that implements "is­a" and/or "has­a" relationships.

Page 30: Section5 scjp6.0

30

Definición de EncapsulaciónMecanismo de la  POO, que permite ocultar y proteger los detalles de la implementación de una clase

Los cambios de implementación de una clase no afectan a las clases cliente de ésta

La clase encapsulada expone sus variables de instancia privadas,a través de métodos públicos

Page 31: Section5 scjp6.0

31

Ejemplo de Encapsulación: El problema public class MyDate{

public int day;

public int month;

public int year;

public MyDate(){ . . . }

public MyDate(int day, int month, int year){ . . . }

}

Código cliente:

MyDate date = new MyDate();

date.day = 32;                           //Error de implementación

date.month = 2; date.day = 31; //Error de implementación

date.day = date.day + 1;           //posible error de implementación

Page 32: Section5 scjp6.0

32

Ejemplo de Encapsulación: La solución  public class MyDate{

private int day;private int month;private int year;public MyDate(){...}public boolean setDay(int day){...}public int getDay(){...}public boolean setMonth(int month){...}public int getMonth(){...}public boolean setYear(int year){...}public int getYear(){...}public boolean addDay(int day){...}

 }

Page 33: Section5 scjp6.0

33

Ejemplo de Encapsulación: La soluciónSolución: 

Definir una encapsulación en la clase MyDate

Declarar  las variables de instancia con el modificador 

privado

Definir métodos públicos de acceso a las variables 

privadas

Cada método Internamente valida el uso de las variables 

de  instancia

Page 34: Section5 scjp6.0

34

Coupling & CohesionCoupling:

Grado de dependencia entre 2 ó más clases

Entre menor sea el grado de Coupling, mayor es la independencia de componentes 

  No Coupling           Loose Coupling

    

                                Tight Coupling

A B A B

A B

Page 35: Section5 scjp6.0

35

Coupling & CohesionCohesion:

Grado de especialización de un componente / clase.

Los componentes de cada clase deben modelar reglas altamente relacionadas entre sí

Entre mas alto sea el grado de Cohesion , mayor especialización del componente y mayor facilidad de mantenimiento.

Ejemplo: Clase coche: 

Debe ocuparse de frenar, acelerar. 

 Es decir define los comportamientos propios de un coche.

   Nota.­ Crear un comportamiento que verifique el seguro del coche. No es parte del alcance o funcionalidad para la que fue creada la clase coche.

Page 36: Section5 scjp6.0

36

Diseño de Clases en Java

Java Herencia simple

En Java podemos heredar de una y sólo una Super Clase

Herencia múltiple emulada a través de las Interfaces

Podemos implementar más de una interface y combinarla con herencia con una clase

Page 37: Section5 scjp6.0

37

Modificadores de AccesoModificadores que permite o no, el uso de algún recurso

Se pueden aplicar a variables de instancia, métodos y clases (nested y top level)

En el caso de clases top level, sólo se pueden usar los modificadores public y default 

Page 38: Section5 scjp6.0

38

HerenciaMecanismo de la POO que permite reutilizar código

Permite definir  a partir de una clase ya existente (super clase), una nueva clase (subclase) que reutilice la definición de métodos y variables definidos por su super clase

Page 39: Section5 scjp6.0

39

Ejemplo de herencia public class Employee{

public  String name;public  double salary;public  Date birthDate;public String getDetails(){...}

}

public class Manager extends Employee{

public  String department;}

Page 40: Section5 scjp6.0

40

Ejemplo de HerenciaLa subclase Manager hereda todos los miembros de su  super clase declarados con el modificador:  protected ó public.

El modificador de acceso private no permite el acceso a miembros heredados.

Page 41: Section5 scjp6.0

41

Relaciones “is a” vs “has a”La relación “es un” es definida a través de una jerarquía de herencia 

La relación “tiene un”  es definida cuando una  ClaseA  tiene una referencia de  una ClaseB

Manager “is a” Employee                            Customer “has a” Account

     class Customer{

                                              private String firstName;                                              private String lastName;

                                                private Account account;

                                           }

                                       class Account{                                              private double balance;                                              private double interestRate;

                                           }

Page 42: Section5 scjp6.0

42

Sobre Escritura de MétodosUna subclase puede modificar el comportamiento de 

algún método heredado de su super clase

La sobre escritura de métodos permite definir una 

nueva implementación para un método  heredado, 

respetando:

Mismo nombre de método

Mismo tipo de retorno, o su covariant

Mismo tipo y lista de argumentos

Page 43: Section5 scjp6.0

43

Sobre Escritura de Métodos

Page 44: Section5 scjp6.0

44

Sobre Escritura de Métodos1.   class Mama{2.       public void bailar(){   System.out.println("baila: Rock & Roll");    }3.   }4.   5.   class HijoA  extends Mama{6.       public void bailar(){   System.out.println("baila: Jazz");      }7.   }8.   9.   class HijoB  extends Mama{10.       public void bailar(){   System.out.println("baila: Tango");   }11.   }12.   13.   class HijoC  extends Mama{14.       public void bailar(){   System.out.println("baila: Danzon"); }15.   }16.   17.   class HijoD extends Mama{}

Page 45: Section5 scjp6.0

45

Ejemplo 2: Sobre Escritura1.   class Object{2.   public String toString(){3.   }4.   }5.   class Employee extends Object{6.       private String name;    7.      private Date birthDate;8.       private double salary;9.      10.       public String toString(){11.                     return " El empleado :"        +  this.getName()  +12.                          " recibe un sueldo de:"         +  this.getSalary() + 13.                          "fecha denaciemiento:"        +  this.getBirthDate();14.       }15.       //getters & setters16. }    

Page 46: Section5 scjp6.0

46

Sobre Escritura: Covariants1.    class SuperType{}2.   class SubType extends SuperType{}3.  4.     class ClassA{5.    public SuperType method(){6.           return null;7.                }8.      }9.  10.       class ClassB extends ClassA{11.       public SubType method(){12.           return null;13.       }14.       }

Page 47: Section5 scjp6.0

47

Continuación: Reglas Sobre Escritura El método sobre escrito debe respetar las siguientes reglas, con respecto a su super método:

Mismo nombre

Mismo tipo de retorno, o su covariant

Misma lista y tipo de argumentos

El modificador de acceso del método de la subclase no puede ser más restrictivo que el de la super clase

Las excepciones que lanza el método sobre escrito, no pueden ser de mayor jerarquía que las excepciones lanzadas por el método en la super clase

Page 48: Section5 scjp6.0

48

Regla: Modificador de acceso

Page 49: Section5 scjp6.0

49

Continuación: Reglas Sobre Escritura El método sobre escrito debe respetar las siguientes reglas, con respecto a su super método:

Mismo nombre

Mismo tipo de retorno, o su covariant

Misma lista y tipo de argumentos

El modificador de acceso del método de la subclase no puede ser más restrictivo que el de la super clase

Las excepciones que lanza el método sobre escrito, no pueden ser de mayor jerarquía que las excepciones lanzadas por el método en la super clase

Page 50: Section5 scjp6.0

50

Regla: Sobre Escritura y Exceptions

Page 51: Section5 scjp6.0

51

Repaso: Categorías  de Excepciones

Page 52: Section5 scjp6.0

52

Sobre Escritura método staticEn la invocación de métodos static sobre escritos, tiene prioridad el método de la clase padre.

   public class A{

public static void metodo(){ System.out.println(“Clase A”); }}

   public class B extends A{

public static void metodo(){System.out.println(“Clase B”); }}

public class TestA{

public static void main(String []args){

A a = new B();a.metodo(); //Invocara el método de la clase padre “Clase A”}

}

Page 53: Section5 scjp6.0

53

PolimorfísmoCaracterística de los lenguajes OO que permiten definir diferentes implementaciones de un mismo método

En Java existe:

Polimorfísmo en métodos

Requiere: Herencia y sobre escritura de métodos

Polimorfísmo  en  Argumentos

El argumento de un método es polimorfo

Page 54: Section5 scjp6.0

54

Polimorfismo en Métodos class  Animal{

public void eat(){

System.out.println(“Generic  Animal eating...”);}

}

class Horse extends Animal{

public void eat(){

System.out.println(“Horse eating...”);}

}

public class TestAnimal{

public static void main(String args[]){

Animal a = new Animal();

Animal b = new Horse();

a.eat();    //method eat()  version Animal Class

b.eat();   //method eat()  version Horse Class

}

}

Page 55: Section5 scjp6.0

55

Polimorfismo en Argumentosclass Figura{ }class Circulo extends Figura{}class Triangulo  extends Figura{}class Rectangulo extends Figura{}

// Otro código...    public void calculaArea(Figura f){        if(f  instanceof Circulo){             // PI * R 2         }else if(f  instanceof  Triangulo){            // B * H /2        }else if(f   instanceof  Rectangulo){            // B * H        }    }

Page 56: Section5 scjp6.0

56

Sobrecarga de MétodosSobre cargar un método se refiere a declarar 2 ó varios métodos en la misma clase con el mismo nombre pero siguiendo las siguientes reglas:

Deben tener diferente lista y tipo de argumentos

Pueden tener diferente tipo de retorno

Pueden tener diferente modificador de acceso

Pueden lanzar Excepciones

El método a sobre cargar puede ser definido en la misma clase o bien en la super clase

Page 57: Section5 scjp6.0

57

Ejemplos válidos de sobre carga de métodospublic class TestOverloaded {    

    public void method(){}

    public void method(int a){}

    public void method(double d){}

    private void method(long i){}

    public boolean method(String  s){

        return false;

    }

    public void method(char c) throws RuntimeException{                

    }

}

Page 58: Section5 scjp6.0

58

Sobrecarga vs Sobre escritura

Page 59: Section5 scjp6.0

59

Concepto de ConstructorSimilar a un método pero con las siguientes reglas:

Mismo nombre de clase

No define tipo de Retorno

Utilizado para crea una nueva instancia de Clase en el Heap

Referencia en Stack, Objeto en el Heap

Si no se define un constructor, Java genera el constructor por default

Page 60: Section5 scjp6.0

60

Sobre carga de constructoresTodas las clases cuentan con un constructor por default

Cualquier definición explícita de un constructor elimina la existencia del constructor por default

Una clase Java permite definir 2 ó más constructores en la misma clase (sobre carga de constructores) 

Un constructor puede invocar a otros constructores de la misma clase a través de this()

Desde un constructor se puede invocar el constructor de su super clase a través de super()

Page 61: Section5 scjp6.0

61

Invocación automática de Constructoresclass Abuelo extends Object{    public Abuelo(){        System.out.println("Constructor de Abuelo()");    }    }class Papa extends Abuelo{    public Papa(){        System.out.println("Constructor de Papa()");    }    }class Hijo extends Papa{    public Hijo(){        System.out.println("Constructor de Hijo()");    }    }

public class TestConstructors {        public static void main(String[] args) {        Abuelo obj = new Hijo();    }    }

Page 62: Section5 scjp6.0

62

Fin de Sección 5:                      OO Concepts

● Notas

● Trabajo en casa

Page 63: Section5 scjp6.0

Asesoría SCJP: Sun Certified Java Programmer 6.0

Sun Educational Services