SlideShare una empresa de Scribd logo
1 de 25
ABSTRACTION
Michael Heron
Introduction
• Abstraction is a process that is important to the creation of
computer programs.
• Being able to view things at a higher level of connection than the
moving parts themselves.
• In this lecture we are going to talk about the nature of
abstraction with regards to object orientation.
• It has both a conceptual and technical meaning.
Designing Classes
• How do classes interact in an object oriented program?
• Passing messages
• How do messages flow through a class architecture?
• Uh…
• Need to understand how all the parts fit together in order
to understand the whole.
• Can’t skip this step and succeed.
Abstraction
• Process of successively filtering out low level details.
• Replace with a high level view of system interactions.
• Helped by the use of diagrams and other notations.
• UML and such
• Important skill in gaining big picture understanding of how
classes interact.
• Vital for applying Design Patterns and other such generalizations.
Abstraction in OO
• Abstraction in OO occurs in two key locations.
• In encapsulated classes
• In abstract classes
• Latter important for developing good object oriented
structures with minimal side effects.
• Sometimes classes simply should not be instantiated.
• They exist to give form and structure, but have no sensible reason
to exist as objects in themselves.
Abstract Classes
• In Java and C++, we can make use of abstract classes to
provide structure with no possibility of implementation.
• These classes cannot be instantiated because they are incomplete
representations.
• These classes provide the necessary contract for C++ to
make use of dynamic binding in a system.
• Must have a derived class which implements all the functionality.
• Known as a concrete class.
Abstract Classes
• In Java, abstract classes created using special syntax for
class declaration:
abstract class Student {
private String matriculationCode;
private String name;
private String address;
public Student (String m, String n, String a) {
matriculationCode = m;
name = n;
address = a;
}
public String getName() {
return name;
}
public String getCode() {
return matriculationCode;
}
public String getAddress() {
return address;
}
}
Abstract Classes
• Individual methods all possible to declare as abstract:
abstract class Student {
private String matriculationCode;
private String name;
private String address;
public Student (String m, String n, String a) {
matriculationCode = m;
name = n;
address = a;
}
public String getName() {
return name;
}
public String getCode() {
return matriculationCode;
}
public String getAddress() {
return address;
}
abstract public int getLoan();
abstract public String getStatus();
}
Abstract Classes
• In C++, classes are made abstract by creating a pure
virtual function.
• Function has no implementation.
• Every concrete class must override all pure virtual
functions.
• Normal virtual gives the option of overriding
• Pure virtual makes overriding mandatory.
virtual void draw() const = 0;
Abstract Classes
• Any class in which a pure virtual is defined is an abstract
class.
• Abstract classes can also contain concrete
implementations and data members.
• Normal rules of invocation and access apply here.
• Can’t instantiate an abstract class…
• … but can use it as the base-line for polymorphism.
Example
• Think back to our chess scenario.
• Baseline Piece class
• Defines a specialisation for each kind of piece.
• Defined a valid_move function in Piece.
• We should never have a Piece object
• Define it as abstract
• Every object must be a specialisation.
• Had a default method for valid_move
• Define it as a pure virtual
• Every object must provide its own implementation.
Intent to Override
• We must explicitly state our intent to over-ride in derived
classes.
• In the class definition:
• void draw() const;
• In the code:
#include "ClassOne.h"
#include <iostream>
using namespace std;
void ClassOne::draw() const {
cout << "Class One Implementation!";
}
Interfaces
• Related idea
• Interfaces
• Supported syntactically in Java
• Must be done somewhat awkwardly in C++
• Interfaces in Java are a way to implement a flavour of multiple
inheritance.
• But only a flavour
interface LibraryAccess {
public boolean canAccessLibrary();
}
Interfaces
public class FullTimeStudent extends Student implements LibraryAccess
{
public FullTimeStudent (String m, String n, String a) {
super (m, n, a);
}
public int getLoan() {
return 1600;
}
public boolean canAccessLibrary() {
return true;
}
public String getStatus() {
return "Full Time";
}
}
Interfaces
• Interfaces permit objects to behave in a polymorphic
manner across multiple kinds of subclasses.
• Both a Student and an instance of the LibraryAccess object.
• Dynamic binding used to deal with this.
• Excellent way of ensuring cross-object compatibility of
method calls and parameters.
• Not present syntactically in C++
Interfaces in C++
• Interfaces defined in C++ using multiple inheritance.
• This is the only time it’s good!
• Define a pure abstract class
• No implementations for anything
• All methods pure virtual
• Inheritance multiple interfaces to give the same effect as a
Java interface.
Interfaces in C++
• Interfaces in C++ are not part of the language.
• They’re a convention we adopt as part of the code.
• Requires rigor to do properly
• You can make a program worse by introducing multiple inheritance
without rigor.
• Interfaces are good
• Use them when they make sense.
Interfaces in C++
class InterfaceClass {
private:
public:
virtual void my_method() const = 0;
};
class SecondInterface {
private:
public:
virtual void my_second_method() const = 0;
};
Interfaces in C++
#include "Interface.h"
#include "SecondInterface.h”
class ClassOne : public InterfaceClass, public SecondInterface {
public:
void my_method() const;
void my_second_method() const;
};
#include "ClassOne.h"
#include <iostream>
using namespace std;
void ClassOne::my_method() const {
cout << "Class One Implementation!" << endl;
}
void ClassOne::my_second_method() const {
cout << "Class One Implementation of second method!" << endl;
}
Interfaces in C++
#include <iostream>
#include "ClassOne.h"
using namespace std;
void do_thing (InterfaceClass *c) {
c->my_method();
}
void do_another_thing (SecondInterface *s) {
s->my_second_method();
}
int main() {
ClassOne *ob;
ob = new ClassOne();
do_thing (ob);
do_another_thing (ob);
return 1;
}
Interfaces Versus Multiple Inheritance
• Interfaces give a flavour of multiple inheritance
• Tastes like chicken
• They handle multiple inheritance in the simplest way
• Separation of abstraction from implementation
• Resolves most of the problems with multiple inheritance.
• No need for conflicting code and management of scope
• Interfaces have no code to go with them.
Interfaces versus Abstract
• Is there a meaningful difference?
• Not in C++
• In Java and C# can…
• Extend one class
• Implement many classes
• In C++
• Can extend many classes
• No baseline support for interfaces
Interfaces versus Abstract
• Why use them?
• No code to carry around
• Enforce polymorphic structure only
• Assumption in an abstract class is that all classes will derive from a
common base.
• Can be hard to implement into an existing class hierarchy.
• Interfaces slot in when needed
• Worth getting used to the distinction.
• OO understand more portable.
More UML Syntax
Abstract class indicated by the use of
italics in attribute and method
names.
Use of interface indicated by two
separate syntactical elements
1. Dotted line headed with an
open arrow
2. Name of class enclosed in
double angle brackets
Summary
• Abstraction important in designing OO programs.
• Abstract classes permit classes to exist with pure virtual
methods.
• Must be overloaded
• Interfaces exist in C# and Java
• Not present syntactically in C++
• Concept is transferable
• Requires rigor of design in C++.

Más contenido relacionado

La actualidad más candente

Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
sawarkar17
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 

La actualidad más candente (20)

Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Java package
Java packageJava package
Java package
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
interface in c#
interface in c#interface in c#
interface in c#
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
GUI programming
GUI programmingGUI programming
GUI programming
 
Methods in java
Methods in javaMethods in java
Methods in java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Inheritance
InheritanceInheritance
Inheritance
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 

Destacado

บทที่ 2 สถาปัตยกรรม
บทที่ 2 สถาปัตยกรรมบทที่ 2 สถาปัตยกรรม
บทที่ 2 สถาปัตยกรรม
PrinceStorm Nueng
 
Degrees of data abstraction
Degrees of data abstractionDegrees of data abstraction
Degrees of data abstraction
Mary May Porto
 
03 data abstraction
03 data abstraction03 data abstraction
03 data abstraction
Opas Kaewtai
 

Destacado (13)

(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation
 
Lec3
Lec3Lec3
Lec3
 
บทที่ 2 สถาปัตยกรรม
บทที่ 2 สถาปัตยกรรมบทที่ 2 สถาปัตยกรรม
บทที่ 2 สถาปัตยกรรม
 
Data abstraction the walls
Data abstraction the wallsData abstraction the walls
Data abstraction the walls
 
Degrees of data abstraction
Degrees of data abstractionDegrees of data abstraction
Degrees of data abstraction
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
03 data abstraction
03 data abstraction03 data abstraction
03 data abstraction
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Slide 3 data abstraction & 3 schema
Slide 3 data abstraction & 3 schemaSlide 3 data abstraction & 3 schema
Slide 3 data abstraction & 3 schema
 
Introduction to Data Abstraction
Introduction to Data AbstractionIntroduction to Data Abstraction
Introduction to Data Abstraction
 
4.1 Defining and visualizing binary relations
4.1 Defining and visualizing binary relations4.1 Defining and visualizing binary relations
4.1 Defining and visualizing binary relations
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 

Similar a 2CPP14 - Abstraction

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 

Similar a 2CPP14 - Abstraction (20)

Abstraction
AbstractionAbstraction
Abstraction
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#
 
Inheritance
InheritanceInheritance
Inheritance
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
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
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Design pattern
Design patternDesign pattern
Design pattern
 
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
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Interface
InterfaceInterface
Interface
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 

Más de Michael Heron

Más de Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Último (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

2CPP14 - Abstraction

  • 2. Introduction • Abstraction is a process that is important to the creation of computer programs. • Being able to view things at a higher level of connection than the moving parts themselves. • In this lecture we are going to talk about the nature of abstraction with regards to object orientation. • It has both a conceptual and technical meaning.
  • 3. Designing Classes • How do classes interact in an object oriented program? • Passing messages • How do messages flow through a class architecture? • Uh… • Need to understand how all the parts fit together in order to understand the whole. • Can’t skip this step and succeed.
  • 4. Abstraction • Process of successively filtering out low level details. • Replace with a high level view of system interactions. • Helped by the use of diagrams and other notations. • UML and such • Important skill in gaining big picture understanding of how classes interact. • Vital for applying Design Patterns and other such generalizations.
  • 5. Abstraction in OO • Abstraction in OO occurs in two key locations. • In encapsulated classes • In abstract classes • Latter important for developing good object oriented structures with minimal side effects. • Sometimes classes simply should not be instantiated. • They exist to give form and structure, but have no sensible reason to exist as objects in themselves.
  • 6. Abstract Classes • In Java and C++, we can make use of abstract classes to provide structure with no possibility of implementation. • These classes cannot be instantiated because they are incomplete representations. • These classes provide the necessary contract for C++ to make use of dynamic binding in a system. • Must have a derived class which implements all the functionality. • Known as a concrete class.
  • 7. Abstract Classes • In Java, abstract classes created using special syntax for class declaration: abstract class Student { private String matriculationCode; private String name; private String address; public Student (String m, String n, String a) { matriculationCode = m; name = n; address = a; } public String getName() { return name; } public String getCode() { return matriculationCode; } public String getAddress() { return address; } }
  • 8. Abstract Classes • Individual methods all possible to declare as abstract: abstract class Student { private String matriculationCode; private String name; private String address; public Student (String m, String n, String a) { matriculationCode = m; name = n; address = a; } public String getName() { return name; } public String getCode() { return matriculationCode; } public String getAddress() { return address; } abstract public int getLoan(); abstract public String getStatus(); }
  • 9. Abstract Classes • In C++, classes are made abstract by creating a pure virtual function. • Function has no implementation. • Every concrete class must override all pure virtual functions. • Normal virtual gives the option of overriding • Pure virtual makes overriding mandatory. virtual void draw() const = 0;
  • 10. Abstract Classes • Any class in which a pure virtual is defined is an abstract class. • Abstract classes can also contain concrete implementations and data members. • Normal rules of invocation and access apply here. • Can’t instantiate an abstract class… • … but can use it as the base-line for polymorphism.
  • 11. Example • Think back to our chess scenario. • Baseline Piece class • Defines a specialisation for each kind of piece. • Defined a valid_move function in Piece. • We should never have a Piece object • Define it as abstract • Every object must be a specialisation. • Had a default method for valid_move • Define it as a pure virtual • Every object must provide its own implementation.
  • 12. Intent to Override • We must explicitly state our intent to over-ride in derived classes. • In the class definition: • void draw() const; • In the code: #include "ClassOne.h" #include <iostream> using namespace std; void ClassOne::draw() const { cout << "Class One Implementation!"; }
  • 13. Interfaces • Related idea • Interfaces • Supported syntactically in Java • Must be done somewhat awkwardly in C++ • Interfaces in Java are a way to implement a flavour of multiple inheritance. • But only a flavour interface LibraryAccess { public boolean canAccessLibrary(); }
  • 14. Interfaces public class FullTimeStudent extends Student implements LibraryAccess { public FullTimeStudent (String m, String n, String a) { super (m, n, a); } public int getLoan() { return 1600; } public boolean canAccessLibrary() { return true; } public String getStatus() { return "Full Time"; } }
  • 15. Interfaces • Interfaces permit objects to behave in a polymorphic manner across multiple kinds of subclasses. • Both a Student and an instance of the LibraryAccess object. • Dynamic binding used to deal with this. • Excellent way of ensuring cross-object compatibility of method calls and parameters. • Not present syntactically in C++
  • 16. Interfaces in C++ • Interfaces defined in C++ using multiple inheritance. • This is the only time it’s good! • Define a pure abstract class • No implementations for anything • All methods pure virtual • Inheritance multiple interfaces to give the same effect as a Java interface.
  • 17. Interfaces in C++ • Interfaces in C++ are not part of the language. • They’re a convention we adopt as part of the code. • Requires rigor to do properly • You can make a program worse by introducing multiple inheritance without rigor. • Interfaces are good • Use them when they make sense.
  • 18. Interfaces in C++ class InterfaceClass { private: public: virtual void my_method() const = 0; }; class SecondInterface { private: public: virtual void my_second_method() const = 0; };
  • 19. Interfaces in C++ #include "Interface.h" #include "SecondInterface.h” class ClassOne : public InterfaceClass, public SecondInterface { public: void my_method() const; void my_second_method() const; }; #include "ClassOne.h" #include <iostream> using namespace std; void ClassOne::my_method() const { cout << "Class One Implementation!" << endl; } void ClassOne::my_second_method() const { cout << "Class One Implementation of second method!" << endl; }
  • 20. Interfaces in C++ #include <iostream> #include "ClassOne.h" using namespace std; void do_thing (InterfaceClass *c) { c->my_method(); } void do_another_thing (SecondInterface *s) { s->my_second_method(); } int main() { ClassOne *ob; ob = new ClassOne(); do_thing (ob); do_another_thing (ob); return 1; }
  • 21. Interfaces Versus Multiple Inheritance • Interfaces give a flavour of multiple inheritance • Tastes like chicken • They handle multiple inheritance in the simplest way • Separation of abstraction from implementation • Resolves most of the problems with multiple inheritance. • No need for conflicting code and management of scope • Interfaces have no code to go with them.
  • 22. Interfaces versus Abstract • Is there a meaningful difference? • Not in C++ • In Java and C# can… • Extend one class • Implement many classes • In C++ • Can extend many classes • No baseline support for interfaces
  • 23. Interfaces versus Abstract • Why use them? • No code to carry around • Enforce polymorphic structure only • Assumption in an abstract class is that all classes will derive from a common base. • Can be hard to implement into an existing class hierarchy. • Interfaces slot in when needed • Worth getting used to the distinction. • OO understand more portable.
  • 24. More UML Syntax Abstract class indicated by the use of italics in attribute and method names. Use of interface indicated by two separate syntactical elements 1. Dotted line headed with an open arrow 2. Name of class enclosed in double angle brackets
  • 25. Summary • Abstraction important in designing OO programs. • Abstract classes permit classes to exist with pure virtual methods. • Must be overloaded • Interfaces exist in C# and Java • Not present syntactically in C++ • Concept is transferable • Requires rigor of design in C++.