SlideShare a Scribd company logo
1 of 16
Abstract Classes and Interfaces
The objectives of this chapter are:
To explore the concept of abstract classes
To understand interfaces
To understand the importance of both.
What is an Abstract class?
Superclasses are created through the process called
"generalization"
Common features (methods or variables) are factored out of object
classifications (ie. classes).
Those features are formalized in a class. This becomes the superclass
The classes from which the common features were taken become
subclasses to the newly created super class
Often, the superclass does not have a "meaning" or does not
directly relate to a "thing" in the real world
It is an artifact of the generalization process
Because of this, abstract classes cannot be instantiated
They act as place holders for abstraction
Vehicle
- make: String
- model: String
- tireCount: int
Car
- trunkCapacity: int
Abstract superclass:
Abstract Class Example
In the following example, the subclasses represent objects
taken from the problem domain.
The superclass represents an abstract concept that does not
exist "as is" in the real world.
Truck
- bedCapacity: int
Note: UML represents abstract
classes by displaying their name
in italics.
What Are Abstract Classes Used For?
Abstract classes are used heavily in Design Patterns
Creational Patterns: Abstract class provides interface for creating
objects. The subclasses do the actual object creation
Structural Patterns: How objects are structured is handled by an
abstract class. What the objects do is handled by the subclasses
Behavioural Patterns: Behavioural interface is declared in an abstract
superclass. Implementation of the interface is provided by subclasses.
Be careful not to over use abstract classes
Every abstract class increases the complexity of your
design
Every subclass increases the complexity of your design
Ensure that you receive acceptable return in terms of functionality given
the added complexity.
Defining Abstract Classes
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object
public abstract class Vehicle
{
private String make;
private String model;
private int tireCount;
[...]
public class Car extends Vehicle
{
private int trunkCapacity;
[...]
Vehicle
- make: String
- model: String
- tireCount: int
Car
- trunkCapacity: int
Truck
- bedCapacity: int
public class Truck extends Vehicle
{
private int bedCapacity;
[...]
Often referred to as "concrete" classes
Abstract Methods
Methods can also be abstracted
An abstract method is one to which a signature has been provided, but
no implementation for that method is given.
An Abstract method is a placeholder. It means that we declare that a
method must exist, but there is no meaningful implementation for that
methods within this class
Any class which contains an abstract method MUST also be
abstract
Any class which has an incomplete method definition cannot
be instantiated (ie. it is abstract)
Abstract classes can contain both concrete and abstract
methods.
If a method can be implemented within an abstract class, and
implementation should be provided.
Abstract Method Example
In the following example, a Transaction's value can be
computed, but there is no meaningful implementation that can
be defined within the Transaction class.
How a transaction is computed is dependent on the transaction's type
Note: This is polymorphism.
Transaction
- computeValue(): int
RetailSale
- computeValue(): int
StockTrade
- computeValue(): int
Defining Abstract Methods
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object
public abstract class Transaction
{
public abstract int computeValue();
public class RetailSale extends Transaction
{
public int computeValue()
{
[...]
Transaction
- computeValue(): int
RetailSale
- computeValue(): int
StockTrade
- computeValue(): int
public class StockTrade extends Transaction
{
public int computeValue()
{
[...]
Note: no implementation
What is an Interface?
An interface is similar to an abstract class with the following
exceptions:
All methods defined in an interface are abstract. Interfaces can contain
no implementation
Interfaces cannot contain instance variables. However, they can
contain public static final variables (ie. constant class variables)
• Interfaces are declared using the "interface" keyword
If an interface is public, it must be contained in a file which
has the same name.
• Interfaces are more abstract than abstract classes
• Interfaces are implemented by classes using the
"implements" keyword.
Declaring an Interface
public interface Steerable
{
public void turnLeft(int degrees);
public void turnRight(int degrees);
}
In Steerable.java:
public class Car extends Vehicle implements Steerable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
In Car.java:
When a class "implements" an
interface, the compiler ensures that
it provides an implementation for
all methods defined within the
interface.
Implementing Interfaces
A Class can only inherit from one superclass. However, a
class may implement several Interfaces
The interfaces that a class implements are separated by commas
• Any class which implements an interface must provide an
implementation for all methods defined within the interface.
NOTE: if an abstract class implements an interface, it NEED NOT
implement all methods defined in the interface. HOWEVER, each
concrete subclass MUST implement the methods defined in the
interface.
• Interfaces can inherit method signatures from other
interfaces.
Declaring an Interface
public class Car extends Vehicle implements Steerable, Driveable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
// implement methods defined within the Driveable interface
In Car.java:
Inheriting Interfaces
If a superclass implements an interface, it's subclasses also
implement the interface
public abstract class Vehicle implements Steerable
{
private String make;
[...]
public class Car extends Vehicle
{
private int trunkCapacity;
[...]
Vehicle
- make: String
- model: String
- tireCount: int
Car
- trunkCapacity: int
Truck
- bedCapacity: int
public class Truck extends Vehicle
{
private int bedCapacity;
[...]
Multiple Inheritance?
Some people (and textbooks) have said that allowing classes
to implement multiple interfaces is the same thing as multiple
inheritance
This is NOT true. When you implement an interface:
The implementing class does not inherit instance variables
The implementing class does not inherit methods (none are defined)
The Implementing class does not inherit associations
Implementation of interfaces is not inheritance. An interface
defines a list of methods which must be implemented.
Interfaces as Types
When a class is defined, the compiler views the class as a
new type.
The same thing is true of interfaces. The compiler regards an
interface as a type.
It can be used to declare variables or method parameters
int i;
Car myFleet[];
Steerable anotherFleet[];
[...]
myFleet[i].start();
anotherFleet[i].turnLeft(100);
anotherFleet[i+1].turnRight(45);
Abstract Classes Versus Interfaces
When should one use an Abstract class instead of an
interface?
If the subclass-superclass relationship is genuinely an "is a"
relationship.
If the abstract class can provide an implementation at the appropriate
level of abstraction
• When should one use an interface in place of an Abstract
Class?
When the methods defined represent a small portion of a class
When the subclass needs to inherit from another class
When you cannot reasonably implement any of the methods

More Related Content

What's hot

Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in javaVishnu Suresh
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Paumil Patel
 

What's hot (20)

Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
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
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 

Viewers also liked

creativity at work fall2015
creativity at work fall2015creativity at work fall2015
creativity at work fall2015Terry Chong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceHarry Potter
 
Búsqueda no informada - Backtracking/Hacia atrás
Búsqueda no informada - Backtracking/Hacia atrásBúsqueda no informada - Backtracking/Hacia atrás
Búsqueda no informada - Backtracking/Hacia atrásLaura Del Pino Díaz
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsJames Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsTony Nguyen
 
Rafael orsini 24118492
Rafael orsini 24118492Rafael orsini 24118492
Rafael orsini 24118492orsini07
 
Prolog Visualizer
Prolog VisualizerProlog Visualizer
Prolog VisualizerZhixuan Lai
 
Power point 1 η μικροδιδασκαλία
Power point 1 η μικροδιδασκαλίαPower point 1 η μικροδιδασκαλία
Power point 1 η μικροδιδασκαλίαMaria Antorka
 
Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16
Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16
Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16John Tzortzakis
 
Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...
Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...
Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...John Tzortzakis
 

Viewers also liked (15)

creativity at work fall2015
creativity at work fall2015creativity at work fall2015
creativity at work fall2015
 
Poo java
Poo javaPoo java
Poo java
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
ΛΟΙΜΩΞΕΙΣ
ΛΟΙΜΩΞΕΙΣΛΟΙΜΩΞΕΙΣ
ΛΟΙΜΩΞΕΙΣ
 
Búsqueda no informada - Backtracking/Hacia atrás
Búsqueda no informada - Backtracking/Hacia atrásBúsqueda no informada - Backtracking/Hacia atrás
Búsqueda no informada - Backtracking/Hacia atrás
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Internet de las cosas
Internet de las cosasInternet de las cosas
Internet de las cosas
 
αγαθα διακρισεις αγαθων
αγαθα διακρισεις αγαθωναγαθα διακρισεις αγαθων
αγαθα διακρισεις αγαθων
 
Rafael orsini 24118492
Rafael orsini 24118492Rafael orsini 24118492
Rafael orsini 24118492
 
Busqueda informada y explorada
Busqueda informada y exploradaBusqueda informada y explorada
Busqueda informada y explorada
 
Prolog Visualizer
Prolog VisualizerProlog Visualizer
Prolog Visualizer
 
Power point 1 η μικροδιδασκαλία
Power point 1 η μικροδιδασκαλίαPower point 1 η μικροδιδασκαλία
Power point 1 η μικροδιδασκαλία
 
Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16
Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16
Εξεταστέα ύλη μαθημάτων της Γ΄τάξης του Τομέα Δομικών Εργων σχ.έτους 2015-16
 
Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...
Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...
Αναλυτικά Προγράμματα Σπουδών Β ́ και Γ ́ τάξεων Τομέα Δομικών Έργων ΦΕΚ 770 ...
 

Similar to Abstract class

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
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Abou Bakr Ashraf
 
Xamarin: Namespace and Classes
Xamarin: Namespace and ClassesXamarin: Namespace and Classes
Xamarin: Namespace and ClassesEng Teong Cheah
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer ProgrammingInocentshuja Ahmad
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS ConceptRicha Gupta
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with JavaJakir Hossain
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1LK394
 

Similar to Abstract class (20)

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
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
Xamarin: Namespace and Classes
Xamarin: Namespace and ClassesXamarin: Namespace and Classes
Xamarin: Namespace and Classes
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
C# program structure
C# program structureC# program structure
C# program structure
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Java basics
Java basicsJava basics
Java basics
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Refactoring Chapter11
Refactoring Chapter11Refactoring Chapter11
Refactoring Chapter11
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with Java
 
Classes2
Classes2Classes2
Classes2
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 

More from Tony Nguyen

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisTony Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceTony Nguyen
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningTony Nguyen
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningTony Nguyen
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryTony Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksTony Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheTony Nguyen
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesTony Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsTony Nguyen
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaTony Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonTony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 

More from Tony Nguyen (20)

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Inheritance
InheritanceInheritance
Inheritance
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Api crash
Api crashApi crash
Api crash
 
Learning python
Learning pythonLearning python
Learning python
 
Python language data types
Python language data typesPython language data types
Python language data types
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Abstract class

  • 1. Abstract Classes and Interfaces The objectives of this chapter are: To explore the concept of abstract classes To understand interfaces To understand the importance of both.
  • 2. What is an Abstract class? Superclasses are created through the process called "generalization" Common features (methods or variables) are factored out of object classifications (ie. classes). Those features are formalized in a class. This becomes the superclass The classes from which the common features were taken become subclasses to the newly created super class Often, the superclass does not have a "meaning" or does not directly relate to a "thing" in the real world It is an artifact of the generalization process Because of this, abstract classes cannot be instantiated They act as place holders for abstraction
  • 3. Vehicle - make: String - model: String - tireCount: int Car - trunkCapacity: int Abstract superclass: Abstract Class Example In the following example, the subclasses represent objects taken from the problem domain. The superclass represents an abstract concept that does not exist "as is" in the real world. Truck - bedCapacity: int Note: UML represents abstract classes by displaying their name in italics.
  • 4. What Are Abstract Classes Used For? Abstract classes are used heavily in Design Patterns Creational Patterns: Abstract class provides interface for creating objects. The subclasses do the actual object creation Structural Patterns: How objects are structured is handled by an abstract class. What the objects do is handled by the subclasses Behavioural Patterns: Behavioural interface is declared in an abstract superclass. Implementation of the interface is provided by subclasses. Be careful not to over use abstract classes Every abstract class increases the complexity of your design Every subclass increases the complexity of your design Ensure that you receive acceptable return in terms of functionality given the added complexity.
  • 5. Defining Abstract Classes Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object public abstract class Vehicle { private String make; private String model; private int tireCount; [...] public class Car extends Vehicle { private int trunkCapacity; [...] Vehicle - make: String - model: String - tireCount: int Car - trunkCapacity: int Truck - bedCapacity: int public class Truck extends Vehicle { private int bedCapacity; [...] Often referred to as "concrete" classes
  • 6. Abstract Methods Methods can also be abstracted An abstract method is one to which a signature has been provided, but no implementation for that method is given. An Abstract method is a placeholder. It means that we declare that a method must exist, but there is no meaningful implementation for that methods within this class Any class which contains an abstract method MUST also be abstract Any class which has an incomplete method definition cannot be instantiated (ie. it is abstract) Abstract classes can contain both concrete and abstract methods. If a method can be implemented within an abstract class, and implementation should be provided.
  • 7. Abstract Method Example In the following example, a Transaction's value can be computed, but there is no meaningful implementation that can be defined within the Transaction class. How a transaction is computed is dependent on the transaction's type Note: This is polymorphism. Transaction - computeValue(): int RetailSale - computeValue(): int StockTrade - computeValue(): int
  • 8. Defining Abstract Methods Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object public abstract class Transaction { public abstract int computeValue(); public class RetailSale extends Transaction { public int computeValue() { [...] Transaction - computeValue(): int RetailSale - computeValue(): int StockTrade - computeValue(): int public class StockTrade extends Transaction { public int computeValue() { [...] Note: no implementation
  • 9. What is an Interface? An interface is similar to an abstract class with the following exceptions: All methods defined in an interface are abstract. Interfaces can contain no implementation Interfaces cannot contain instance variables. However, they can contain public static final variables (ie. constant class variables) • Interfaces are declared using the "interface" keyword If an interface is public, it must be contained in a file which has the same name. • Interfaces are more abstract than abstract classes • Interfaces are implemented by classes using the "implements" keyword.
  • 10. Declaring an Interface public interface Steerable { public void turnLeft(int degrees); public void turnRight(int degrees); } In Steerable.java: public class Car extends Vehicle implements Steerable { public int turnLeft(int degrees) { [...] } public int turnRight(int degrees) { [...] } In Car.java: When a class "implements" an interface, the compiler ensures that it provides an implementation for all methods defined within the interface.
  • 11. Implementing Interfaces A Class can only inherit from one superclass. However, a class may implement several Interfaces The interfaces that a class implements are separated by commas • Any class which implements an interface must provide an implementation for all methods defined within the interface. NOTE: if an abstract class implements an interface, it NEED NOT implement all methods defined in the interface. HOWEVER, each concrete subclass MUST implement the methods defined in the interface. • Interfaces can inherit method signatures from other interfaces.
  • 12. Declaring an Interface public class Car extends Vehicle implements Steerable, Driveable { public int turnLeft(int degrees) { [...] } public int turnRight(int degrees) { [...] } // implement methods defined within the Driveable interface In Car.java:
  • 13. Inheriting Interfaces If a superclass implements an interface, it's subclasses also implement the interface public abstract class Vehicle implements Steerable { private String make; [...] public class Car extends Vehicle { private int trunkCapacity; [...] Vehicle - make: String - model: String - tireCount: int Car - trunkCapacity: int Truck - bedCapacity: int public class Truck extends Vehicle { private int bedCapacity; [...]
  • 14. Multiple Inheritance? Some people (and textbooks) have said that allowing classes to implement multiple interfaces is the same thing as multiple inheritance This is NOT true. When you implement an interface: The implementing class does not inherit instance variables The implementing class does not inherit methods (none are defined) The Implementing class does not inherit associations Implementation of interfaces is not inheritance. An interface defines a list of methods which must be implemented.
  • 15. Interfaces as Types When a class is defined, the compiler views the class as a new type. The same thing is true of interfaces. The compiler regards an interface as a type. It can be used to declare variables or method parameters int i; Car myFleet[]; Steerable anotherFleet[]; [...] myFleet[i].start(); anotherFleet[i].turnLeft(100); anotherFleet[i+1].turnRight(45);
  • 16. Abstract Classes Versus Interfaces When should one use an Abstract class instead of an interface? If the subclass-superclass relationship is genuinely an "is a" relationship. If the abstract class can provide an implementation at the appropriate level of abstraction • When should one use an interface in place of an Abstract Class? When the methods defined represent a small portion of a class When the subclass needs to inherit from another class When you cannot reasonably implement any of the methods