SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
Java Programming –
Abstract Class & Interface
Oum Saokosal
Master’s Degree in information systems,Jeonju
University,South Korea
012 252 752 / 070 252 752
oumsaokosal@gmail.com
Contact Me
• Tel: 012 252 752 / 070 252 752
• Email: oumsaokosal@gmail.com
• FB Page: https://facebook.com/kosalgeek
• PPT: http://www.slideshare.net/oumsaokosal
• YouTube: https://www.youtube.com/user/oumsaokosal
• Twitter: https://twitter.com/okosal
• Web: http://kosalgeek.com
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 implementationfor
all methods definedwithin 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

Contenu connexe

Tendances

Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 

Tendances (20)

Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
Generics
GenericsGenerics
Generics
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Abstract class
Abstract classAbstract class
Abstract class
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Java exception
Java exception Java exception
Java exception
 

En vedette

Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo
Erika Hall
 

En vedette (20)

Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - SwingJava OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for Android
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Java
 
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with ExamplesJavascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo Copy As Interface | Erika Hall | Web 2.0 Expo
Copy As Interface | Erika Hall | Web 2.0 Expo
 
Java interface
Java interfaceJava interface
Java interface
 
Measuring And Defining The Experience Of Immersion In Games
Measuring And  Defining The  Experience Of  Immersion In GamesMeasuring And  Defining The  Experience Of  Immersion In Games
Measuring And Defining The Experience Of Immersion In Games
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)ITS (Intelligent Teleportation System)
ITS (Intelligent Teleportation System)
 
Terminology In Telecommunication
Terminology In TelecommunicationTerminology In Telecommunication
Terminology In Telecommunication
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
 

Similaire à Java OOP Programming language (Part 6) - Abstract Class & Interface

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 

Similaire à Java OOP Programming language (Part 6) - Abstract Class & Interface (20)

Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
C# program structure
C# program structureC# program structure
C# program structure
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
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
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
iOS development introduction
iOS development introduction iOS development introduction
iOS development introduction
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 

Plus de OUM SAOKOSAL

Aggregate rank bringing order to web sites
Aggregate rank  bringing order to web sitesAggregate rank  bringing order to web sites
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
How to succeed in graduate school
How to succeed in graduate schoolHow to succeed in graduate school
How to succeed in graduate school
OUM SAOKOSAL
 
Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
Consumer acceptance of online banking an extension of the technology accepta...
Consumer acceptance of online banking  an extension of the technology accepta...Consumer acceptance of online banking  an extension of the technology accepta...
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
Correlation Example
Correlation ExampleCorrelation Example
Correlation Example
OUM SAOKOSAL
 
Path Spss Amos (1)
Path Spss Amos (1)Path Spss Amos (1)
Path Spss Amos (1)
OUM SAOKOSAL
 
How To Succeed In Graduate School
How To Succeed In Graduate SchoolHow To Succeed In Graduate School
How To Succeed In Graduate School
OUM SAOKOSAL
 

Plus de OUM SAOKOSAL (20)

Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum Saokosal
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Java OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to JavaJava OOP Programming language (Part 1) - Introduction to Java
Java OOP Programming language (Part 1) - Introduction to Java
 
Aggregate rank bringing order to web sites
Aggregate rank  bringing order to web sitesAggregate rank  bringing order to web sites
Aggregate rank bringing order to web sites
 
How to succeed in graduate school
How to succeed in graduate schoolHow to succeed in graduate school
How to succeed in graduate school
 
Google
GoogleGoogle
Google
 
E miner
E minerE miner
E miner
 
Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)Data preparation for mining world wide web browsing patterns (1999)
Data preparation for mining world wide web browsing patterns (1999)
 
Consumer acceptance of online banking an extension of the technology accepta...
Consumer acceptance of online banking  an extension of the technology accepta...Consumer acceptance of online banking  an extension of the technology accepta...
Consumer acceptance of online banking an extension of the technology accepta...
 
When Do People Help
When Do People HelpWhen Do People Help
When Do People Help
 
Mc Nemar
Mc NemarMc Nemar
Mc Nemar
 
Correlation Example
Correlation ExampleCorrelation Example
Correlation Example
 
Sem Ski Amos
Sem Ski AmosSem Ski Amos
Sem Ski Amos
 
Sem+Essentials
Sem+EssentialsSem+Essentials
Sem+Essentials
 
Path Spss Amos (1)
Path Spss Amos (1)Path Spss Amos (1)
Path Spss Amos (1)
 
Kimchi Questionnaire
Kimchi QuestionnaireKimchi Questionnaire
Kimchi Questionnaire
 
How To Succeed In Graduate School
How To Succeed In Graduate SchoolHow To Succeed In Graduate School
How To Succeed In Graduate School
 
Actionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other NoteActionscript 3 - Session 7 Other Note
Actionscript 3 - Session 7 Other Note
 
Actionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core ConceptActionscript 3 - Session 4 Core Concept
Actionscript 3 - Session 4 Core Concept
 
Actionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And FlashActionscript 3 - Session 3 Action Script And Flash
Actionscript 3 - Session 3 Action Script And Flash
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Java OOP Programming language (Part 6) - Abstract Class & Interface

  • 1. Java Programming – Abstract Class & Interface Oum Saokosal Master’s Degree in information systems,Jeonju University,South Korea 012 252 752 / 070 252 752 oumsaokosal@gmail.com
  • 2. Contact Me • Tel: 012 252 752 / 070 252 752 • Email: oumsaokosal@gmail.com • FB Page: https://facebook.com/kosalgeek • PPT: http://www.slideshare.net/oumsaokosal • YouTube: https://www.youtube.com/user/oumsaokosal • Twitter: https://twitter.com/okosal • Web: http://kosalgeek.com
  • 3. 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.
  • 4. 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
  • 5. 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.
  • 6. 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.
  • 7. 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
  • 8. 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.
  • 9. 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
  • 10. 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
  • 11. 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.
  • 12. 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 implementationfor all methods definedwithin the interface.
  • 13. 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.
  • 14. 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:
  • 15. 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; [...]
  • 16. 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.
  • 17. 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);
  • 18. 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