SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
Abstract classes and interfaces
Sérgio Souza Costa
Universidade Federaldo Maranhão
27 de junho de 2016
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 1 / 23
Based in the Java In Nutshell.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 2 / 23
Summary
Introduction
Abstract methods and class
Defining an Interface
Interfaces vs. Abstract Classes
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 3 / 23
Introduction
Suppose we plan to implement a number of shape classes: Rectangle, Square, Ellipse,
Triangle, and so on.
We can give these shape classes our two basic area( ) and circumference() methods.
We want the Shape class to encapsulate whatever features all our shapes have in common
(e.g., the area() and circumference( ) methods). But our generic Shape class doesn’t
represent any real kind of shape, so it cannot define useful implementations of the
methods.
Java handles this situation with abstract methods.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 4 / 23
Abstract methods and class
Java lets us define a method without implementing it by declaring the method with the
abstract modifier.
An abstract method has no body; it simply has a signature definition followed by a
semicolon
An abstract method in Java is something like a pure virtual function in C++ (i.e., a
virtual func- tion that is declared = 0). In C++, a class that contains a pure virtual
function is called an abstract class and cannot be instantiated. The same is true of Java
classes that contain abstract methods.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 5 / 23
Abstract methods and class
Rules about abstract methods and the abstract classes that contain them:
1 Any class with an abstract method is automatically abstract itself and must be declared as
such.
2 An abstract class cannot be instantiated.
3 A subclass of an abstract class can be instantiated only if it overrides each of the
abstract methods of its superclass and provides an implementation (i.e., a method body)
for all of them. Such a class is often called a concrete subclass, to emphasize the fact
that it is not abstract.
4 If a subclass of an abstract class does not implement all the abstract methods it inherits,
that subclass is itself abstract and must be declared as such.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 6 / 23
Abstract methods and class
5 static, private, and final methods cannot be abstract since these types of methods cannot
be overridden by a subclass. Similarly, a final class cannot contain any abstract methods.
6 A class can be declared abstract even if it does not actually have any abstract methods.
Declaring such a class abstract indicates that the implementation is somehow incomplete
and is meant to serve as a superclass for one or more sub- classes that complete the
implementation. Such a class cannot be instantiated.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 7 / 23
Example - Circle
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference(); // semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r;
public Circle(double r) { this.r = r; }
public double getRadius() { return r; }
public double area() { return PI*r*r; }
public double circumference() { return 2*PI*r; }
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 8 / 23
Example - Rectangle
class Rectangle extends Shape {
protected double w, h;
public Rectangle(double w, double h) {
this.w = w;
this.h = h;
}
public double getWidth() { return w; }
public double getHeight() { return h; }
public double area() { return w*h; }
public double circumference() { return 2*(w + h); }
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 9 / 23
Example - Test
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(2.0);
shapes[1] = new Rectangle(1.0, 3.0);
shapes[2] = new Rectangle(4.0, 2.0);
double total_area = 0;
for(int i = 0; i < shapes.length; i++)
total_area += shapes[i].area();
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 10 / 23
Abstract class - Final remarks
Subclasses of Shape can be assigned to elements of an array of Shape. No cast is
necessary.
You can invoke the area() and circumference() methods for any Shape object, even though
the Shape class does not define a body for these methods. When you do this, the method
to be invoked is found using dynamic method lookup, so the area of a circle is computed
using the method defined by Circle, and the area of a rectangle is computed using the
method defined by Rectangle.
Exercícios
Testem as classes Shape, Circle, Rectangle e Test
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 11 / 23
Interfaces
As its name implies, an interface specifies only an API: all of its methods are abstract and
have no bodies.
It is not possible to directly instantiate an interface and create a member of the interface
type. Instead, a class must implement the interface to provide the necessary method
bodies.
Interfaces provide a limited but very powerful alternative to multiple inheritance.* Classes
in Java can inherit members from only a single superclass, but they can implement
any number of interfaces.
Observação
C++ supports multiple inheritance, but the ability of a class to have more than one superclass
adds a lot of complexity to the language.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 12 / 23
Defining an Interface
An interface definition is much like a class definition in which all the methods are abstract
and the keyword class has been replaced with interface.
For example, the following code shows the definition of an interface named Centered.
public interface Centered {
void setCenter(double x, double y);
double getCenterX();
double getCenterY();
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 13 / 23
Defining an Interface
A number of restrictions apply to the members of an interface:
1 An interface contains no implementation whatsoever. All methods of an interface are
implicitly abstract and must have a semicolon in place of a method body. The abstract
modifier is allowed but, by convention, is usually omitted. Since static methods may not
be abstract, the methods of an interface may not be declared static.
2 An interface defines a public API. All members of an interface are implicitly public, and it
is conventional to omit the unnecessary public modifier. It is an error to define a protected
or private method in an interface.
3 An interface may not define any instance fields. Fields are an implementation detail, and
an interface is a pure specification without any implementation. The only fields allowed in
an interface definition are constants that are declared both static and final.
4 An interface cannot be instantiated, so it does not define a constructor.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 14 / 23
Implementing an Interface
If a class implements an interface but does not provide an implementation for every
interface method, it inherits those unimplemented abstract methods from the interface
and must itself be declared abstract.
If a class implements more than one interface, it must implement every method of each
interface it implements (or be declared abstract).
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 15 / 23
Implementing an Interface
The following code shows how we can define a CenteredRectangle class that extends the
Rectangle class from earlier and implements our Centered interface.
public class CenteredRectangle extends Rectangle implements Centered {
private double cx, cy;
public CenteredRectangle(double cx, double cy, double w, double h) {
super(w, h);
this.cx = cx;
this.cy = cy;
}
// provide implementations of all the Centered methods.
public void setCenter(double x, double y) { cx = x; cy = y; }
public double getCenterX() { return cx; }
public double getCenterY() { return cy; }
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 16 / 23
Example - Test (1)
Shape[] shapes = new Shape[3]; // Create an array to hold shapes
// Create some centered shapes, and store them in the Shape[]
// No cast necessary: these are all widening conversions
shapes[0] = new CenteredCircle(1.0, 1.0, 1.0);
shapes[1] = new CenteredSquare(2.5, 2, 3);
shapes[2] = new CenteredRectangle(2.3, 4.5, 3, 4);
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 17 / 23
Example - Test (2)
// Compute average area of the shapes and average distance from the origin
double totalArea = 0;
double totalDistance = 0;
for(int i = 0; i < shapes.length; i++) {
totalArea += shapes[i].area(); // Compute the area of the shapes
if (shapes[i] instanceof Centered) {
Centered c = (Centered) shapes[i]; // required cast.
double cx = c.getCenterX();
double cy = c.getCenterY();
totalDistance += Math.sqrt(cx*cx + cy*cy)
}
}
System.out.println("Average area: " + totalArea/shapes.length);
System.out.println("Average distance: " + totalDistance/shapes.length);
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 18 / 23
Atividade
Exercícios
Atualizem o projeto do exercicio anterior, adicionando a interface Centered e as classes
CenteredCircle, CenteredSquare e CenteredRectangle. Testem estas classes com os codigos
apresentados aqui.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 19 / 23
Interfaces vs. Abstract Classes
An interface is a pure API specification and contains no implementation. If an interface
has numerous methods, it can become tedious to implement the methods over and over,
especially when much of the implementation is duplicated by each implementing class.
An abstract class does not need to be entirely abstract; it can contain a partial
implementation that subclasses can take advantage of. In some cases, numerous
subclasses can rely on default method implementations provided by an abstract class.
But a class that extends an abstract class cannot extend any other class, which can cause
design difficulties in some situations.
Another important difference between interfaces and abstract classes has to do with
compatibility. If you define an interface as part of a public API and then later add a new
method to the interface, you break any classes that implemented the previous version of
the interface.
If you use an abstract class, however, you can safely add nonabstract methods to that
class without requiring modifications to existing classes that extend the abstract class.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 20 / 23
Interfaces vs. Abstract Classes
In some situations, it is clear that an interface or an abstract class is the right design
choice. In other cases, a common design pattern is to use both.
// Here is a basic interface. It represents a shape that fits inside
// of a rectangular bounding box. Any class that wants to serve as a
// RectangularShape can implement these methods from scratch.
public interface RectangularShape {
void setSize(double width, double height);
void setPosition(double x, double y);
void translate(double dx, double dy);
double area();
boolean isInside();
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 21 / 23
Interfaces vs. Abstract Classes
// Here is a partial implementation of that interface. Many
// implementations may find this a useful starting point.
public abstract class AbstractRectangularShape implements RectangularShape {
// The position and size of the shape
protected double x, y, w, h;
// Default implementations of some of the interface methods
public void setSize(double width, double height) { w = width; h = height; }
public void setPosition(double x, double y) { this.x = x; this.y = y; }
public void translate (double dx, double dy) { x += dx; y += dy; }
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 22 / 23
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 23 / 23

Mais conteúdo relacionado

Mais procurados

Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceOum Saokosal
 
Relações (composição e agregação)
Relações (composição e agregação)Relações (composição e agregação)
Relações (composição e agregação)Sérgio Souza Costa
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentationtigerwarn
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism JavaM. Raihan
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear ASHNA nadhm
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAhmed Nobi
 
Java interfaces
Java interfacesJava interfaces
Java interfacesjehan1987
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces Tuan Ngo
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 

Mais procurados (20)

Abstract method
Abstract methodAbstract method
Abstract method
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
javainterface
javainterfacejavainterface
javainterface
 
Relações (composição e agregação)
Relações (composição e agregação)Relações (composição e agregação)
Relações (composição e agregação)
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Abstract classes
Abstract classesAbstract classes
Abstract classes
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
Poo java
Poo javaPoo java
Poo java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 

Destaque

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
 
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
 
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
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...
Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...
Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...Nelson Glauber Leal
 
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
 
Interfaces Inteligentes para Android
Interfaces Inteligentes para AndroidInterfaces Inteligentes para Android
Interfaces Inteligentes para AndroidNelson Glauber Leal
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend classAbhishek Wadhwa
 

Destaque (20)

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
 
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
 
Contextualizando o moodle
Contextualizando o moodleContextualizando o moodle
Contextualizando o moodle
 
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
 
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 ?
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Palestra android
Palestra androidPalestra android
Palestra android
 
Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...
Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...
Campus Party Recife - Sua primeira e próximas aplicações Android: como fazer ...
 
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++
 
Interfaces Inteligentes para Android
Interfaces Inteligentes para AndroidInterfaces Inteligentes para Android
Interfaces Inteligentes para Android
 
Criando um App com App Inventor 2
Criando um App com App Inventor 2Criando um App com App Inventor 2
Criando um App com App Inventor 2
 
Google apps script - Parte - 1
Google apps script - Parte - 1Google apps script - Parte - 1
Google apps script - Parte - 1
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 

Semelhante a Abstract classes and interfaces

Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and InterfacesJamsher bhanbhro
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
ABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.pptABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.pptJayanthiM15
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Abstract_descrption
Abstract_descrptionAbstract_descrption
Abstract_descrptionMahi Mca
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالMahmoud Alfarra
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13Vince Vo
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
Abstract class and interface
Abstract class and interfaceAbstract class and interface
Abstract class and interfaceMazharul Sabbir
 
06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programmingdeffa5
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxssuser84e52e
 

Semelhante a Abstract classes and interfaces (20)

Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
ABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.pptABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.ppt
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Abstract_descrption
Abstract_descrptionAbstract_descrption
Abstract_descrption
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Abstract class and interface
Abstract class and interfaceAbstract class and interface
Abstract class and interface
 
Oop
OopOop
Oop
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming
 
Java interface
Java interface Java interface
Java interface
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
 

Mais de 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
 
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
 
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
 

Mais de Sérgio Souza Costa (16)

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

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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...apidays
 
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...Martijn de Jong
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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 WorkerThousandEyes
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Abstract classes and interfaces

  • 1. Abstract classes and interfaces Sérgio Souza Costa Universidade Federaldo Maranhão 27 de junho de 2016 Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 1 / 23
  • 2. Based in the Java In Nutshell. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 2 / 23
  • 3. Summary Introduction Abstract methods and class Defining an Interface Interfaces vs. Abstract Classes Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 3 / 23
  • 4. Introduction Suppose we plan to implement a number of shape classes: Rectangle, Square, Ellipse, Triangle, and so on. We can give these shape classes our two basic area( ) and circumference() methods. We want the Shape class to encapsulate whatever features all our shapes have in common (e.g., the area() and circumference( ) methods). But our generic Shape class doesn’t represent any real kind of shape, so it cannot define useful implementations of the methods. Java handles this situation with abstract methods. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 4 / 23
  • 5. Abstract methods and class Java lets us define a method without implementing it by declaring the method with the abstract modifier. An abstract method has no body; it simply has a signature definition followed by a semicolon An abstract method in Java is something like a pure virtual function in C++ (i.e., a virtual func- tion that is declared = 0). In C++, a class that contains a pure virtual function is called an abstract class and cannot be instantiated. The same is true of Java classes that contain abstract methods. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 5 / 23
  • 6. Abstract methods and class Rules about abstract methods and the abstract classes that contain them: 1 Any class with an abstract method is automatically abstract itself and must be declared as such. 2 An abstract class cannot be instantiated. 3 A subclass of an abstract class can be instantiated only if it overrides each of the abstract methods of its superclass and provides an implementation (i.e., a method body) for all of them. Such a class is often called a concrete subclass, to emphasize the fact that it is not abstract. 4 If a subclass of an abstract class does not implement all the abstract methods it inherits, that subclass is itself abstract and must be declared as such. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 6 / 23
  • 7. Abstract methods and class 5 static, private, and final methods cannot be abstract since these types of methods cannot be overridden by a subclass. Similarly, a final class cannot contain any abstract methods. 6 A class can be declared abstract even if it does not actually have any abstract methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a superclass for one or more sub- classes that complete the implementation. Such a class cannot be instantiated. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 7 / 23
  • 8. Example - Circle public abstract class Shape { public abstract double area(); // Abstract methods: note public abstract double circumference(); // semicolon instead of body. } class Circle extends Shape { public static final double PI = 3.14159265358979323846; protected double r; public Circle(double r) { this.r = r; } public double getRadius() { return r; } public double area() { return PI*r*r; } public double circumference() { return 2*PI*r; } } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 8 / 23
  • 9. Example - Rectangle class Rectangle extends Shape { protected double w, h; public Rectangle(double w, double h) { this.w = w; this.h = h; } public double getWidth() { return w; } public double getHeight() { return h; } public double area() { return w*h; } public double circumference() { return 2*(w + h); } } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 9 / 23
  • 10. Example - Test Shape[] shapes = new Shape[3]; shapes[0] = new Circle(2.0); shapes[1] = new Rectangle(1.0, 3.0); shapes[2] = new Rectangle(4.0, 2.0); double total_area = 0; for(int i = 0; i < shapes.length; i++) total_area += shapes[i].area(); Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 10 / 23
  • 11. Abstract class - Final remarks Subclasses of Shape can be assigned to elements of an array of Shape. No cast is necessary. You can invoke the area() and circumference() methods for any Shape object, even though the Shape class does not define a body for these methods. When you do this, the method to be invoked is found using dynamic method lookup, so the area of a circle is computed using the method defined by Circle, and the area of a rectangle is computed using the method defined by Rectangle. Exercícios Testem as classes Shape, Circle, Rectangle e Test Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 11 / 23
  • 12. Interfaces As its name implies, an interface specifies only an API: all of its methods are abstract and have no bodies. It is not possible to directly instantiate an interface and create a member of the interface type. Instead, a class must implement the interface to provide the necessary method bodies. Interfaces provide a limited but very powerful alternative to multiple inheritance.* Classes in Java can inherit members from only a single superclass, but they can implement any number of interfaces. Observação C++ supports multiple inheritance, but the ability of a class to have more than one superclass adds a lot of complexity to the language. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 12 / 23
  • 13. Defining an Interface An interface definition is much like a class definition in which all the methods are abstract and the keyword class has been replaced with interface. For example, the following code shows the definition of an interface named Centered. public interface Centered { void setCenter(double x, double y); double getCenterX(); double getCenterY(); } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 13 / 23
  • 14. Defining an Interface A number of restrictions apply to the members of an interface: 1 An interface contains no implementation whatsoever. All methods of an interface are implicitly abstract and must have a semicolon in place of a method body. The abstract modifier is allowed but, by convention, is usually omitted. Since static methods may not be abstract, the methods of an interface may not be declared static. 2 An interface defines a public API. All members of an interface are implicitly public, and it is conventional to omit the unnecessary public modifier. It is an error to define a protected or private method in an interface. 3 An interface may not define any instance fields. Fields are an implementation detail, and an interface is a pure specification without any implementation. The only fields allowed in an interface definition are constants that are declared both static and final. 4 An interface cannot be instantiated, so it does not define a constructor. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 14 / 23
  • 15. Implementing an Interface If a class implements an interface but does not provide an implementation for every interface method, it inherits those unimplemented abstract methods from the interface and must itself be declared abstract. If a class implements more than one interface, it must implement every method of each interface it implements (or be declared abstract). Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 15 / 23
  • 16. Implementing an Interface The following code shows how we can define a CenteredRectangle class that extends the Rectangle class from earlier and implements our Centered interface. public class CenteredRectangle extends Rectangle implements Centered { private double cx, cy; public CenteredRectangle(double cx, double cy, double w, double h) { super(w, h); this.cx = cx; this.cy = cy; } // provide implementations of all the Centered methods. public void setCenter(double x, double y) { cx = x; cy = y; } public double getCenterX() { return cx; } public double getCenterY() { return cy; } } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 16 / 23
  • 17. Example - Test (1) Shape[] shapes = new Shape[3]; // Create an array to hold shapes // Create some centered shapes, and store them in the Shape[] // No cast necessary: these are all widening conversions shapes[0] = new CenteredCircle(1.0, 1.0, 1.0); shapes[1] = new CenteredSquare(2.5, 2, 3); shapes[2] = new CenteredRectangle(2.3, 4.5, 3, 4); Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 17 / 23
  • 18. Example - Test (2) // Compute average area of the shapes and average distance from the origin double totalArea = 0; double totalDistance = 0; for(int i = 0; i < shapes.length; i++) { totalArea += shapes[i].area(); // Compute the area of the shapes if (shapes[i] instanceof Centered) { Centered c = (Centered) shapes[i]; // required cast. double cx = c.getCenterX(); double cy = c.getCenterY(); totalDistance += Math.sqrt(cx*cx + cy*cy) } } System.out.println("Average area: " + totalArea/shapes.length); System.out.println("Average distance: " + totalDistance/shapes.length); Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 18 / 23
  • 19. Atividade Exercícios Atualizem o projeto do exercicio anterior, adicionando a interface Centered e as classes CenteredCircle, CenteredSquare e CenteredRectangle. Testem estas classes com os codigos apresentados aqui. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 19 / 23
  • 20. Interfaces vs. Abstract Classes An interface is a pure API specification and contains no implementation. If an interface has numerous methods, it can become tedious to implement the methods over and over, especially when much of the implementation is duplicated by each implementing class. An abstract class does not need to be entirely abstract; it can contain a partial implementation that subclasses can take advantage of. In some cases, numerous subclasses can rely on default method implementations provided by an abstract class. But a class that extends an abstract class cannot extend any other class, which can cause design difficulties in some situations. Another important difference between interfaces and abstract classes has to do with compatibility. If you define an interface as part of a public API and then later add a new method to the interface, you break any classes that implemented the previous version of the interface. If you use an abstract class, however, you can safely add nonabstract methods to that class without requiring modifications to existing classes that extend the abstract class. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 20 / 23
  • 21. Interfaces vs. Abstract Classes In some situations, it is clear that an interface or an abstract class is the right design choice. In other cases, a common design pattern is to use both. // Here is a basic interface. It represents a shape that fits inside // of a rectangular bounding box. Any class that wants to serve as a // RectangularShape can implement these methods from scratch. public interface RectangularShape { void setSize(double width, double height); void setPosition(double x, double y); void translate(double dx, double dy); double area(); boolean isInside(); } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 21 / 23
  • 22. Interfaces vs. Abstract Classes // Here is a partial implementation of that interface. Many // implementations may find this a useful starting point. public abstract class AbstractRectangularShape implements RectangularShape { // The position and size of the shape protected double x, y, w, h; // Default implementations of some of the interface methods public void setSize(double width, double height) { w = width; h = height; } public void setPosition(double x, double y) { this.x = x; this.y = y; } public void translate (double dx, double dy) { x += dx; y += dy; } } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 22 / 23
  • 23. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 27 de junho de 2016 23 / 23