SlideShare a Scribd company logo
1 of 23
Download to read offline
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
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
Conteúdo
Introdução
Herança
Encapsulamento
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 3 / 22
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 o
acesso e a compreensão do codigo existente dentro do tipo.
5 Problema 2 Muitas modelagens tratam de categorias de objetos que são relacionados de
modo 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
Exemplo
public class Circle {
public static final double PI = 3.14159; // A constant
public double r; // An instance field that holds the radius of the circ
// The constructor method: initialize the radius field
public Circle(double r) { this.r = r; }
// The instance methods: compute values based on the radius
public 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
Exemplo
public class PlaneCircle extends Circle {
// New instance fields that store the center point of the circle
public 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
Exemplo
PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0); // Unit circle at the origin
double ratio = pc.circumference() / pc.area();
Circle c = pc; // Assigned to a Circle variable without casting
Observação
Every PlaneCircle object is also a perfectly legal Circle object. If pc refers to a PlaneCircle
object, 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
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 an
extends 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
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
Superclasses, Object, and the Class Hierarchy
Because every class has a superclass, classes in Java form a class hierarchy, which can be
represented 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
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ção
This constructor explicitly initializes the cx and cy fields newly defined by PlaneCircle, but it
relies on the superclass Circle( ) constructor to initialize the inherited fields of the class. To
invoke 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
Hiding Superclass Fields
Imagine that our PlaneCircle class needs to know the distance between the center of the
circle 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 field
of PlaneCircle. How, then, can we refer to the field r of Circle that holds the radius of the
circle?
r // Refers to the PlaneCircle field
this.r // Refers to the PlaneCircle field
super.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
Hiding Superclass Fields
Another way to refer to a hidden field is to cast this (or any instance of the class) to the
appropriate 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 field
defined in a class that is not the immediate superclass. Suppose, for example, that classes
A, B, and C.
this.x // Field x in class C
super.x // Field x in class B
((B)this).x // Field x in class B
((A)this).x // Field x in class A
super.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
Overriding Superclass Methods
When a class defines an instance method using the same name, return type, and
parameters as a method in its superclass, that method overrides the method of the
superclass.
When the method is invoked for an object of the class, it is the new definition of the
method that is called, not the superclass’s old definition.
Method overriding is an important and useful technique in object-oriented programming.
Não confunda
Method overloading refers to the practice of defining multiple methods (in the same class) that
have 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
Overriding is not hiding
Although Java treats the fields and methods of a class analogously in many ways, method
overriding 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
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 1
Experimente 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
Data Hiding and Encapsulation
Encapsulation: One of the important object-oriented techniques is hiding the data within the
class 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. If
you prevent programmers from relying on those details, you can safely modify the
implementation without worrying that you will break existing code that uses the class.
Another reason for encapsulation is to protect your class against accidental or willful
stupidity. A class often contains a number of interdependent fields that must be in a
consistent state.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 17 / 22
Data Hiding and Encapsulation
Esclarecendo
When all the data for a class is hidden, the methods define the only possible operations that
can be performed on objects of that class. Once you have carefully tested and debugged your
methods, you can be confident that the class will work as expected. On the other hand, if all
the fields of the class can be directly manipulated, the number of possibilities you have to test
becomes unmanageable.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 18 / 22
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 outside
the class.
This public keyword, along with protected and private, are access control modifiers; they
specify 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
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 package
itself is accessible).
inner classes: Because the inner classes are members of a class, they obey the member
access-control rules.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 20 / 22
Access to members
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 21 / 22
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 to
make fields non-public and encapsulate them with public accessor methods.
Use protected for fields and methods that aren’t required by most programmers using the
class but that may be of interest to anyone creating a subclass as part of a different
package. 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 code
that relies on them.
Use private for fields and methods that are used only inside the class and should be hidden
everywhere else.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 22 / 22
Access to members
Observação
If you are not sure whether to use protected, package, or private accessibility, it is better to
start with overly restrictive member access. You can always relax the access restrictions in
future versions of your class, if necessary. Doing the reverse is not a good idea because
increasing access restrictions is not a backward- compatible change and can break code that
relies on access to those members.
Atividade 2
Reescrevam 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

More Related Content

What's hot

Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism JavaM. Raihan
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2sotlsoc
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةMahmoud Alfarra
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالMahmoud Alfarra
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية Mahmoud Alfarra
 
Java assignment help
Java assignment helpJava assignment help
Java assignment helpJacob William
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classesAnup Burange
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 

What's hot (19)

Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 

Viewers also liked

DBCells - an open and global multi-scale linked cells
DBCells - an open and global multi-scale linked cellsDBCells - an open and global multi-scale linked cells
DBCells - an open and global multi-scale linked cellsSérgio Souza Costa
 
Paradigma orientado a objetos - Caso de Estudo C++
Paradigma orientado a objetos - Caso de Estudo C++Paradigma orientado a objetos - Caso de Estudo C++
Paradigma orientado a objetos - Caso de Estudo C++Sérgio Souza Costa
 
Conceitos básicos de orientação a objetos
Conceitos básicos de orientação a objetosConceitos básicos de orientação a objetos
Conceitos básicos de orientação a objetosSérgio Souza Costa
 
Desafios para a modelagem de sistemas terrestres (2008)
Desafios para a modelagem de sistemas terrestres (2008)Desafios para a modelagem de sistemas terrestres (2008)
Desafios para a modelagem de sistemas terrestres (2008)Sérgio Souza Costa
 
Informação Geográfica nos Dispositivos Móveis
Informação Geográfica nos Dispositivos MóveisInformação Geográfica nos Dispositivos Móveis
Informação Geográfica nos Dispositivos MóveisSérgio Souza Costa
 
From remote sensing to agent-based models
From remote sensing to agent-based modelsFrom remote sensing to agent-based models
From remote sensing to agent-based modelsSérgio Souza Costa
 
AppInventor - Conhecendo o ambiente e seus principais componentes
AppInventor - Conhecendo o ambiente e seus principais componentesAppInventor - Conhecendo o ambiente e seus principais componentes
AppInventor - Conhecendo o ambiente e seus principais componentesSérgio Souza Costa
 
Explorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficosExplorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficosSérgio Souza Costa
 
AppInventor - Blocos condicionais e explorando alguns recursos do smartphone
AppInventor - Blocos condicionais e explorando alguns recursos do smartphoneAppInventor - Blocos condicionais e explorando alguns recursos do smartphone
AppInventor - Blocos condicionais e explorando alguns recursos do smartphoneSérgio Souza Costa
 
Explorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento ComputacionalExplorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento ComputacionalSérgio Souza Costa
 
Árvores: Conceitos e binárias
Árvores:  Conceitos e bináriasÁrvores:  Conceitos e binárias
Árvores: Conceitos e bináriasSérgio Souza Costa
 
O fim dos SIGs: Como isso ira lhe_afetar ?
O fim dos SIGs: Como isso ira lhe_afetar ?O fim dos SIGs: Como isso ira lhe_afetar ?
O fim dos SIGs: Como isso ira lhe_afetar ?Sérgio Souza Costa
 

Viewers also liked (20)

DBCells - an open and global multi-scale linked cells
DBCells - an open and global multi-scale linked cellsDBCells - an open and global multi-scale linked cells
DBCells - an open and global multi-scale linked cells
 
Paradigma orientado a objetos - Caso de Estudo C++
Paradigma orientado a objetos - Caso de Estudo C++Paradigma orientado a objetos - Caso de Estudo C++
Paradigma orientado a objetos - Caso de Estudo C++
 
Google apps script - Parte - 1
Google apps script - Parte - 1Google apps script - Parte - 1
Google apps script - Parte - 1
 
Google apps script - Parte 2
Google apps script - Parte 2Google apps script - Parte 2
Google apps script - Parte 2
 
Árvores balanceadas - AVL
Árvores balanceadas - AVLÁrvores balanceadas - AVL
Árvores balanceadas - AVL
 
Conceitos básicos de orientação a objetos
Conceitos básicos de orientação a objetosConceitos básicos de orientação a objetos
Conceitos básicos de orientação a objetos
 
Desafios para a modelagem de sistemas terrestres (2008)
Desafios para a modelagem de sistemas terrestres (2008)Desafios para a modelagem de sistemas terrestres (2008)
Desafios para a modelagem de sistemas terrestres (2008)
 
Informação Geográfica nos Dispositivos Móveis
Informação Geográfica nos Dispositivos MóveisInformação Geográfica nos Dispositivos Móveis
Informação Geográfica nos Dispositivos Móveis
 
From remote sensing to agent-based models
From remote sensing to agent-based modelsFrom remote sensing to agent-based models
From remote sensing to agent-based models
 
App inventor - aula 03
App inventor  - aula 03App inventor  - aula 03
App inventor - aula 03
 
Software
SoftwareSoftware
Software
 
AppInventor - Conhecendo o ambiente e seus principais componentes
AppInventor - Conhecendo o ambiente e seus principais componentesAppInventor - Conhecendo o ambiente e seus principais componentes
AppInventor - Conhecendo o ambiente e seus principais componentes
 
Explorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficosExplorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficos
 
AppInventor - Blocos condicionais e explorando alguns recursos do smartphone
AppInventor - Blocos condicionais e explorando alguns recursos do smartphoneAppInventor - Blocos condicionais e explorando alguns recursos do smartphone
AppInventor - Blocos condicionais e explorando alguns recursos do smartphone
 
Contextualizando o moodle
Contextualizando o moodleContextualizando o moodle
Contextualizando o moodle
 
Explorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento ComputacionalExplorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento Computacional
 
Comandos e expressões
Comandos e expressõesComandos e expressões
Comandos e expressões
 
Árvores: Conceitos e binárias
Árvores:  Conceitos e bináriasÁrvores:  Conceitos e binárias
Árvores: Conceitos e binárias
 
Funções e procedimentos
Funções e procedimentosFunções e procedimentos
Funções e procedimentos
 
O fim dos SIGs: Como isso ira lhe_afetar ?
O fim dos SIGs: Como isso ira lhe_afetar ?O fim dos SIGs: Como isso ira lhe_afetar ?
O fim dos SIGs: Como isso ira lhe_afetar ?
 

Similar to Herança e Encapsulamento

Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorialBui Kiet
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)quantumiq448
 
Java Basics
Java BasicsJava Basics
Java BasicsF K
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance SlidesAhsan Raja
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.pptParikhitGhosh1
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.pptRassjb
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 

Similar to Herança e Encapsulamento (20)

Java02
Java02Java02
Java02
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java basic
Java basicJava basic
Java basic
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
Java basics
Java basicsJava basics
Java basics
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Inheritance
InheritanceInheritance
Inheritance
 

More from Sérgio Souza Costa

Expressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicasExpressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicasSérgio Souza Costa
 
De algoritmos à programas de computador
De algoritmos à programas de computadorDe algoritmos à programas de computador
De algoritmos à programas de computadorSérgio Souza Costa
 
Introdução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmosIntrodução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmosSérgio Souza Costa
 
Minicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficosMinicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficosSérgio Souza Costa
 
Banco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de EncerramentoBanco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de EncerramentoSérgio Souza Costa
 
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagemBanco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagemSérgio Souza Costa
 
Banco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de aberturaBanco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de aberturaSérgio Souza Costa
 
Linguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - IntroduçãoLinguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - IntroduçãoSérgio Souza Costa
 
Gödel’s incompleteness theorems
Gödel’s incompleteness theoremsGödel’s incompleteness theorems
Gödel’s incompleteness theoremsSérgio Souza Costa
 
Aula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computaçãoAula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computaçãoSérgio Souza Costa
 

More from Sérgio Souza Costa (15)

Expressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicasExpressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicas
 
De algoritmos à programas de computador
De algoritmos à programas de computadorDe algoritmos à programas de computador
De algoritmos à programas de computador
 
Introdução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmosIntrodução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmos
 
Minicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficosMinicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficos
 
Modelagem de dados geográficos
Modelagem de dados geográficosModelagem de dados geográficos
Modelagem de dados geográficos
 
Banco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de EncerramentoBanco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de Encerramento
 
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagemBanco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
 
Banco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de aberturaBanco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de abertura
 
Linguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - IntroduçãoLinguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - Introdução
 
Gödel’s incompleteness theorems
Gödel’s incompleteness theoremsGödel’s incompleteness theorems
Gödel’s incompleteness theorems
 
Turing e o problema da decisão
Turing e o problema da decisãoTuring e o problema da decisão
Turing e o problema da decisão
 
Introdução ao Prolog
Introdução ao PrologIntrodução ao Prolog
Introdução ao Prolog
 
Heap - Python
Heap - PythonHeap - Python
Heap - Python
 
Paradigma lógico
Paradigma lógicoParadigma lógico
Paradigma lógico
 
Aula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computaçãoAula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computação
 

Recently uploaded

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Herança e Encapsulamento

  • 1. 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
  • 2. 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
  • 3. Conteúdo Introdução Herança Encapsulamento Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 3 / 22
  • 4. 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 o acesso e a compreensão do codigo existente dentro do tipo. 5 Problema 2 Muitas modelagens tratam de categorias de objetos que são relacionados de modo 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
  • 5. Exemplo public class Circle { public static final double PI = 3.14159; // A constant public double r; // An instance field that holds the radius of the circ // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } // The instance methods: compute values based on the radius public 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
  • 6. Exemplo public class PlaneCircle extends Circle { // New instance fields that store the center point of the circle public 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
  • 7. Exemplo PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0); // Unit circle at the origin double ratio = pc.circumference() / pc.area(); Circle c = pc; // Assigned to a Circle variable without casting Observação Every PlaneCircle object is also a perfectly legal Circle object. If pc refers to a PlaneCircle object, 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
  • 8. 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 an extends 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
  • 9. 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
  • 10. Superclasses, Object, and the Class Hierarchy Because every class has a superclass, classes in Java form a class hierarchy, which can be represented 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
  • 11. 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ção This constructor explicitly initializes the cx and cy fields newly defined by PlaneCircle, but it relies on the superclass Circle( ) constructor to initialize the inherited fields of the class. To invoke 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
  • 12. Hiding Superclass Fields Imagine that our PlaneCircle class needs to know the distance between the center of the circle 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 field of PlaneCircle. How, then, can we refer to the field r of Circle that holds the radius of the circle? r // Refers to the PlaneCircle field this.r // Refers to the PlaneCircle field super.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
  • 13. Hiding Superclass Fields Another way to refer to a hidden field is to cast this (or any instance of the class) to the appropriate 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 field defined in a class that is not the immediate superclass. Suppose, for example, that classes A, B, and C. this.x // Field x in class C super.x // Field x in class B ((B)this).x // Field x in class B ((A)this).x // Field x in class A super.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
  • 14. Overriding Superclass Methods When a class defines an instance method using the same name, return type, and parameters as a method in its superclass, that method overrides the method of the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, not the superclass’s old definition. Method overriding is an important and useful technique in object-oriented programming. Não confunda Method overloading refers to the practice of defining multiple methods (in the same class) that have 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
  • 15. Overriding is not hiding Although Java treats the fields and methods of a class analogously in many ways, method overriding 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
  • 16. 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 1 Experimente 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
  • 17. Data Hiding and Encapsulation Encapsulation: One of the important object-oriented techniques is hiding the data within the class 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. If you prevent programmers from relying on those details, you can safely modify the implementation without worrying that you will break existing code that uses the class. Another reason for encapsulation is to protect your class against accidental or willful stupidity. A class often contains a number of interdependent fields that must be in a consistent state. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 17 / 22
  • 18. Data Hiding and Encapsulation Esclarecendo When all the data for a class is hidden, the methods define the only possible operations that can be performed on objects of that class. Once you have carefully tested and debugged your methods, you can be confident that the class will work as expected. On the other hand, if all the fields of the class can be directly manipulated, the number of possibilities you have to test becomes unmanageable. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 18 / 22
  • 19. 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 outside the class. This public keyword, along with protected and private, are access control modifiers; they specify 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
  • 20. 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 package itself is accessible). inner classes: Because the inner classes are members of a class, they obey the member access-control rules. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 20 / 22
  • 21. Access to members Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 21 / 22
  • 22. 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 to make fields non-public and encapsulate them with public accessor methods. Use protected for fields and methods that aren’t required by most programmers using the class but that may be of interest to anyone creating a subclass as part of a different package. 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 code that relies on them. Use private for fields and methods that are used only inside the class and should be hidden everywhere else. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 21 de junho de 2016 22 / 22
  • 23. Access to members Observação If you are not sure whether to use protected, package, or private accessibility, it is better to start with overly restrictive member access. You can always relax the access restrictions in future versions of your class, if necessary. Doing the reverse is not a good idea because increasing access restrictions is not a backward- compatible change and can break code that relies on access to those members. Atividade 2 Reescrevam 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