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 - 2
PRN USM
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
sotlsoc
 
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
Sunil Kumar Gunasekaran
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
DevMix
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

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

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
 
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óveis
Sérgio Souza Costa
 
Árvores: Conceitos e binárias
Árvores:  Conceitos e bináriasÁrvores:  Conceitos e binárias
Árvores: Conceitos e binárias
Sé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 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
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 

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

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
Sé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

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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