Apresentação da semana 10 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
2. Da aula anterior… Operação toString Classes, instâncias e objectos Leituras com Scanner 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 2
3. Encapsulação Aplica ocultação de informação a elemento de linguagem Oculta implementação e revela interface Produtores: acesso exclusivoà implementação Consumidores: acedem apenas a interface Resultado são módulos Rotinas Objectos/classes Pacotes 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 3 Ou “encapsulamento”. A ver mais tarde.
4. Interface vs. implementação Interface Como se usa? O que faz? Qual o contrato entre produtor e consumidor? Implementação Como funciona? Qual o mecanismo? 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 4
5. Encapsulação: vantagens Implementação pode mudar sem afectar consumidores Produtores podem garantir bom comportamento dos módulos Mais fácil localizar erros Mais fácil corrigir erros Facilita abstracção do consumidor! 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 5
6. Encapsulação: interface Métodos e rotinas Cabeçalho apenas Classes Operações Propriedades … 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 6
7. Encapsulação: implementação Métodos e rotinas Corpo apenas Classes Métodos auxiliares Métodos enquanto implementação de operações Atributos … 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 7
9. { if (m == 0 && n == 0) thrownew IllegalArgumentException("Illegal call with " + "m = 0 and n = 0."); m = Math.abs(m); n = Math.abs(n); if (m == 0 || n == 0) return Math.max(m, n); intpossibleGcd = Math.min(m, n); while (m % possibleGcd != 0 || n % possibleGcd != 0) possibleGcd--; returnpossibleGcd; } /** * Returns the greatest common divisor (GCD) of two integer numbers. * * @param m first of the two integer numbers whose GCD will be returned. * @param n second of the two integer numbers whose GCD will be returned. * @return the greatest common divisor of m and n. * @pre m ≠ 0 ∨n ≠ 0 * @post gcd = gcd(m, n) */ publicstaticintgcd(intm, intn) 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 9 Interface: o que faz, contrato. { if (m == 0 && n == 0) thrownew IllegalArgumentException("Illegal call with " + "m = 0 and n = 0."); m = Math.abs(m); n = Math.abs(n); if (m == 0 || n == 0) return Math.max(m, n); intpossibleGcd = Math.min(m, n); while (m % possibleGcd != 0 || n % possibleGcd != 0) possibleGcd--; returnpossibleGcd; } Interface: como se usa. Implementação: como funciona.
10. /** * Returns the greatest common divisor (GCD) of two integer numbers. * * @param m first of the two integer numbers whose GCD will be returned. * @param n second of the two integer numbers whose GCD will be returned. * @return the greatest common divisor of m and n. * @pre m ≠ 0 ∨n ≠ 0 * @post gcd = gcd(m, n) */ publicstaticintgcd(intm, intn) 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 10 public staticintgcd(int m, intn) { if (m == 0 && n == 0) thrownew IllegalArgumentException("Illegal call with " + "m = 0 and n = 0."); m = Math.abs(m); n = Math.abs(n); while (m != 0) { inttemporary = m; m = n % m; n = temporary; } returnn; } /** * Returns the greatest common divisor (GCD) of two integer numbers. * * @param m first of the two integer numbers whose GCD will be returned. * @param n second of the two integer numbers whose GCD will be returned. * @return the greatest common divisor of m and n. * @pre m ≠ 0 ∨n ≠ 0 * @post gcd = gcd(m, n) */ publicstaticintgcd(intm, intn) Implementação alternativa: funcionamento diferente. Mesma interface: usa-se da mesma forma, faz o mesmo.
20. Cópia de instâncias Cópia com inicialização e atribuição afecta apenas referências! Necessário construtor por cópia publicclass Point { … public Point(final Point aPoint) { abscissa= aPoint.getAbscissa(); ordinate= aPoint.getOrdinate(); } … privatefinalintabscissa; privatefinalintordinate; } Point a = newPoint(1.0, -2.0); Point b = a; Point c = new Point(a); 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 19 a b c (1; -2) (1; -2)
21. Igualdade de instâncias Operador == com referências verifica identidade e não igualdades! Necessária operação! publicclass Point { … publicbooleanisEqualTo( final Point aPoint) { returngetAbscissa() == aPoint.getAbscissa() && getOrdinate() == aPoint.getOrdinate(); } … } Point a = newPoint(1.0, -2.0); Point b = a; Point c = new Point(a); 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 20 Mais tarde usaremos equals(). a b c (1; -2) (1; -2) b == a? Sim. c == a? Não! b.isEqualTo(a)? Sim. c.isEqualTo(a)? Sim!
22. A reter Encapsulação em Java Abstracção Módulos em Java Interface vs. implementação Modificadores de acesso public eprivate Vantagens da encapsulação Cópia de instâncias usando construtor Igualdade entre instâncias usando método 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 21
23. A ler... Capítulos 8 e 9 do livro: Y. Daniel Liang, Introduction to Java Programming, 8.ª edição, Prentice-Hall, 2010. ISBN: 978-0-13-213080-6 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 22
24. Sumário Encapsulamento Cópia de instâncias Igualdade entre instâncias 2010/2011 Introdução à Programação - DCTI - ISCTE-IUL 23