Herança e Encapsulamento

23
Herança e encapsulamento Sérgio Souza Costa Universidade Federaldo Maranhão 21 de junho de 2016 Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 1 / 22

Transcript of Herança e Encapsulamento

Page 1: Herança e Encapsulamento

Herança e encapsulamento

Sérgio Souza Costa

Universidade Federaldo Maranhão

21 de junho de 2016

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 1 / 22

Page 2: Herança e Encapsulamento

Os slides a seguir foram retirados do livro Java In Nutshell.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 2 / 22

Page 3: Herança e Encapsulamento

Conteúdo

IntroduçãoHerançaEncapsulamento

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 3 / 22

Page 4: Herança e Encapsulamento

Introdução

1 A reusabilidade é uma qualidade desejavel no desenvolvimento de grandes sistemas.2 Tipos abstratos de dados (TAD), com seu encapsulamento e controle de acesso, são as

unidades de reuso nas linguagens orientadas a objetos.3 TADs em linguagens orientadas a objetos são chamadas de classes, e suas instâncias de

objetos.4 Problema 1: As capacidades de um tipo existente podem não atender plenamente as

necessidades da aplicação cliente, requerendo adaptações. Porém, isso iria requerer oacesso e a compreensão do codigo existente dentro do tipo.

5 Problema 2 Muitas modelagens tratam de categorias de objetos que são relacionados demodo hierárquico, como relações de pais e filhos.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 4 / 22

Page 5: Herança e Encapsulamento

Exemplo

public class Circle {public static final double PI = 3.14159; // A constantpublic double r; // An instance field that holds the radius of the circle// The constructor method: initialize the radius fieldpublic Circle(double r) { this.r = r; }// The instance methods: compute values based on the radiuspublic double circumference() { return 2 * PI * r; }public double area() { return PI * r*r; }

}

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 5 / 22

Page 6: Herança e Encapsulamento

Exemplo

public class PlaneCircle extends Circle {// New instance fields that store the center point of the circlepublic double cx, cy;public PlaneCircle(double r, double x, double y) {

super(r);this.cx = x;this.cy = y;

}public boolean isInside(double x, double y) {

double dx = x - cx, dy = y - cy;double distance = Math.sqrt(dx*dx + dy*dy);return (distance < r);

}}

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 6 / 22

Page 7: Herança e Encapsulamento

Exemplo

PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0); // Unit circle at the origindouble ratio = pc.circumference() / pc.area();Circle c = pc; // Assigned to a Circle variable without casting

ObservaçãoEvery PlaneCircle object is also a perfectly legal Circle object. If pc refers to a PlaneCircleobject, we can assign it to a Circle variable and forget all about its extra positioning capabilities

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 7 / 22

Page 8: Herança e Encapsulamento

Superclasses, Object, and the Class Hierarchy

In our example, PlaneCircle is a subclass from Circle.We can also say that Circle is the superclass of PlaneCircle.The superclass of a class is specified in its extends clause:public class PlaneCircle extends Circle { ... }

Every class you define has a superclass. If you do not specify the superclass with anextends clause, the superclass is the class java.lang.Object.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 8 / 22

Page 9: Herança e Encapsulamento

Superclasses, Object, and the Class Hierarchy

Object is a special class for a couple of reasons:

It is the only class in Java that does not have a superclass.All Java classes inherit the methods of Object.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 9 / 22

Page 10: Herança e Encapsulamento

Superclasses, Object, and the Class Hierarchy

Because every class has a superclass, classes in Java form a class hierarchy, which can berepresented as a tree with Object at its root.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 10 / 22

Page 11: Herança e Encapsulamento

Subclass Constructors

Look again at the PlaneCircle() constructor method:public PlaneCircle(double r, double x, double y) {

super(r);this.cx = x;this.cy = y;

}

ObservaçãoThis constructor explicitly initializes the cx and cy fields newly defined by PlaneCircle, but itrelies on the superclass Circle( ) constructor to initialize the inherited fields of the class. Toinvoke the superclass constructor, our constructor calls super().

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 11 / 22

Page 12: Herança e Encapsulamento

Hiding Superclass Fields

Imagine that our PlaneCircle class needs to know the distance between the center of thecircle and the origin (0,0).public double r;this.r = Math.sqrt(cx*cx + cy*cy); // Pythagorean theorem

With this new definition of PlaneCircle, the expressions r and this.r both refer to the fieldof PlaneCircle. How, then, can we refer to the field r of Circle that holds the radius of thecircle?r // Refers to the PlaneCircle fieldthis.r // Refers to the PlaneCircle fieldsuper.r // Refers to the Circle field

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 12 / 22

Page 13: Herança e Encapsulamento

Hiding Superclass Fields

Another way to refer to a hidden field is to cast this (or any instance of the class) to theappropriate superclass and then access the field:((Circle) this).r // Refers to field r of the Circle class

This casting technique is particularly useful when you need to refer to a hidden fielddefined in a class that is not the immediate superclass. Suppose, for example, that classesA, B, and C.this.x // Field x in class Csuper.x // Field x in class B((B)this).x // Field x in class B((A)this).x // Field x in class Asuper.super.x // Illegal; does not refer to x in class A

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 13 / 22

Page 14: Herança e Encapsulamento

Overriding Superclass Methods

When a class defines an instance method using the same name, return type, andparameters as a method in its superclass, that method overrides the method of thesuperclass.When the method is invoked for an object of the class, it is the new definition of themethod that is called, not the superclass’s old definition.Method overriding is an important and useful technique in object-oriented programming.

Não confundaMethod overloading refers to the practice of defining multiple methods (in the same class) thathave the same name but different parameter lists.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 14 / 22

Page 15: Herança e Encapsulamento

Overriding is not hiding

Although Java treats the fields and methods of a class analogously in many ways, methodoverriding is not like field hiding at all.class A {int i= 1;int f() { return i; }static char g() { return ’A’; }}class B extends A {int i = 2;int f() { return -i; }static char g() { return ’B’; }}

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 15 / 22

Page 16: Herança e Encapsulamento

Overriding is not hiding: test

B b = new B();System.out.println(b.i);System.out.println(b.f());System.out.println(b.g());System.out.println(B.g());A a = (A) b;System.out.println(a.i);System.out.println(a.f());System.out.println(a.g());System.out.println(A.g());

Atividade 1Experimente e explique a execução deste teste.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 16 / 22

Page 17: Herança e Encapsulamento

Data Hiding and Encapsulation

Encapsulation: One of the important object-oriented techniques is hiding the data within theclass and making it available only through the methods. Why would you want to do this?

The most important reason is to hide the internal implementation details of your class. Ifyou prevent programmers from relying on those details, you can safely modify theimplementation without worrying that you will break existing code that uses the class.Another reason for encapsulation is to protect your class against accidental or willfulstupidity. A class often contains a number of interdependent fields that must be in aconsistent state.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 17 / 22

Page 18: Herança e Encapsulamento

Data Hiding and Encapsulation

EsclarecendoWhen all the data for a class is hidden, the methods define the only possible operations thatcan be performed on objects of that class. Once you have carefully tested and debugged yourmethods, you can be confident that the class will work as expected. On the other hand, if allthe fields of the class can be directly manipulated, the number of possibilities you have to testbecomes unmanageable.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 18 / 22

Page 19: Herança e Encapsulamento

Access Control

All the fields and methods of a class can always be used within the body of the class itself.Java defines access control rules that restrict members of a class from being used outsidethe class.This public keyword, along with protected and private, are access control modifiers; theyspecify the access rules for the field or method.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 19 / 22

Page 20: Herança e Encapsulamento

Access to classes (top-leve and inner)

top-level: By default, are accessible within the package in which they are defined.However, if is declared public, it is accessible everywhere (or everywhere that the packageitself is accessible).inner classes: Because the inner classes are members of a class, they obey the memberaccess-control rules.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 20 / 22

Page 21: Herança e Encapsulamento

Access to members

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 21 / 22

Page 22: Herança e Encapsulamento

Access to members

Simple rules of thumb for using visibility modifiers:

Use public only for methods and constants that form part of the public API of the class.Certain important or frequently used fields can also be public, but it is common practice tomake fields non-public and encapsulate them with public accessor methods.Use protected for fields and methods that aren’t required by most programmers using theclass but that may be of interest to anyone creating a subclass as part of a differentpackage. Note that protected members are technically part of the exported API of a class.They should be documented and cannot be changed without potentially breaking codethat relies on them.Use private for fields and methods that are used only inside the class and should be hiddeneverywhere else.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 22 / 22

Page 23: Herança e Encapsulamento

Access to members

ObservaçãoIf you are not sure whether to use protected, package, or private accessibility, it is better tostart with overly restrictive member access. You can always relax the access restrictions infuture versions of your class, if necessary. Doing the reverse is not a good idea becauseincreasing access restrictions is not a backward- compatible change and can break code thatrelies on access to those members.

Atividade 2Reescrevam as classe Circle e PlaneCircle, incluindo o controle de acesso.

Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 23 / 22