SlideShare a Scribd company logo
1 of 19
Download to read offline
Abstract Class & Interface
Object Oriented Programming
By: Engr. Jamsher Bhanbhro
Lecturer at Department of Computer Systems Engineering, Mehran
University of Engineering & Technology Jamshoro
9/26/2023 Object Oriented Programming (22CSSECII)
Books Recommendation
Books Recommended
1. Head First Java by Kathy Sierra & Bert Bates.
2. Beginning Programming with Java For Dummies by Barry Burd
3. Java: Programming Basics for Absolute Beginners by Nathan Clark
4. Object Oriented Programming in Java by Rick Halterman
Websites Recommended:
DataFlair, Educative, course era
Abstract Classes
• A class that is declared with abstract keyword, is known as abstract class
in java. It can have abstract and non-abstract methods (method with body).
Syntax
public abstract class Shape{
public abstract void Draw( ); // Abstract method without definition
public void Display( ) {
System.out.println(“Display Method of Shape class”);
}
}
Abstract & Non-Abstract Methods
Abstract Methods
• An abstract method is a method declared in an
abstract class (or an interface) without
providing a method body (i.e., without
implementation).
• It is declared using the abstract keyword.
• Subclasses that extend the abstract class (or
implement the interface) are required to
provide an implementation for all abstract
methods. If they don't, the subclass must also
be declared as abstract.
• Abstract methods define a contract that
concrete subclasses must follow.
abstract class Animal {
public abstract void makeSound(); // Abstract
//method with no implementation
}
Non-Abstract Methods
• Non-Abstract Methods are Called Concrete
Methods
• A non-abstract method is a method that has a
complete implementation in the class where it
is declared.
• Non-abstract methods have a method body
containing code that defines their behavior.
• Subclasses can inherit non-abstract methods as
they are or override them to provide custom
behavior.
public void run() {
System.out.println("The dog is running.");
}
Abstraction in Java
• Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
• Another way, it shows only important things to the user and hides the
internal details for example sending sms, you just type the text and
send the message. You don't know the internal processing about the
message delivery.
• Abstraction lets you focus on what the object does instead of how it
does it.
Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)
Abstract Classes
➢A class must be declared abstract if any of the following condition is
true
− The class has one or more abstract methods
− The class inherits one or more abstract methods for which it does not provide
implementation
− The class declares that it implements an interface but does not provide
implementation for every method of that interface
Abstract Classes
➢An abstract class cannot be instantiated / Object Can’t be created.
− Abstract classes defer the implementation to subclasses
− The subclass must provide the implementation of the abstract method or declare
itself to be abstract in which case the implementation is deferred once again
➢You can declare a variable/reference of an abstract class.
Abstract Class Example
public abstract class LivingThing {
public void breath( ){
System.out.println("Living Thing breathing..."); }
public void eat( ){
System.out.println("Living Thing eating..."); }
public abstract void walk( );
}
public class Human extends LivingThing {
public void walk( ){
System.out.println("Human walks..."); }
}
Public static void main(String args[]){
Human ob = new Human();
ob.walk();
ob.breath();
}
}
Abstract Class Example
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw( ){
System.out.println("drawing rectangle"); }
}
class Circle1 extends Shape{
void draw( ){
System.out.println("drawing circle"); }
}
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1( );
s.draw( );
}
}
If you are extending any abstract class that have
abstract method, you must either provide the
implementation of the method or make this class
abstract.
Abstract Method in Abstract Class
• An abstract method cannot be contained in a non-abstract class.
• If a subclass of an abstract superclass does not implement all the abstract
methods, the subclass must be defined abstract.
• In other words, in a non-abstract subclass extended from an abstract class, all
the abstract methods must be implemented, even if they are not used in the
subclass.
Abstract Class
//In Java It is possible to create abstract class without abstract methods too.
abstract class Shape {
private String color;
// A non-abstract (concrete) method
public void setColor(String color) {
this.color = color;
}
// Another non-abstract method
public String getColor() {
return color;}
// A constructor
public Shape(String color) {
this.color = color;}
}
An-other Example of Abstract Class
abstract class Shape {
// Abstract method (no implementation in the abstract class)
public abstract double calculateArea();
// Concrete method (provides a default implementation)
public void printDetails() {
System.out.println("This is a shape."); }
}
class Rectangle extends Shape {
private double length; private double width;
public Rectangle(double length, double width) {
this.length = length; this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius; }
public double calculateArea() {
return Math.PI * radius * radius; }
public static void main(String[] args) {
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
// Calculate and print the areas
double circleArea = circle.calculateArea();
System.out.println("Circle Area: " + circleArea);
System.out.println("Rectangle Area: " + rectangle.calculateArea);
circle.printDetails();
rectangle.printDetails(); }
}
Interface In Java
• An interface is a blueprint for a set of methods that a class must
implement. It defines a contract of method signatures that classes can
adhere to, allowing for a common way to access related functionality
across different classes and supporting multiple inheritance of method
signatures. Essentially, an interface outlines what methods a class
should provide without specifying how they are implemented.
• Interfaces are used to achieve abstraction, provide a common way to
access related functionality across different classes, and support
multiple inheritance of method signatures.
• Declaration: You define an interface using the interface keyword,
followed by the interface's name and a list of method signatures.
Interface In Java
• Declaration
interface MyInterface {
void printName();
int add(int a, int b);
}
Methods: Interfaces can contain abstract method declarations. These methods
do not have a method body (implementation). Any class that implements the
interface must provide concrete implementations for all the methods declared
in the interface.
Constants: Interfaces can also contain constant declarations (fields) that are
implicitly public, static, and final. These fields are typically used for defining
constants that are relevant to the interface.
Interface In Java
• Implementing an Interface: To implement an interface, a class uses the
implements keyword. A class can implement multiple interfaces. When a
class implements an interface, it must provide concrete implementations for
all the methods declared in the interface.
class MyClass implements MyInterface {
@Override
public void printName() {
System.out.println(“22CS MUET”);
}
@Override
public add(int a, int b) {
a+b;
}
}
Interface Example
public interface Shape {
double calculateArea();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
//create main method yourself
}
Abstract Vs Interface
Feature Abstract Class Interface
Syntax Declared using the abstract keyword. Declared using the interface keyword.
Instantiation Cannot be instantiated directly. Cannot be instantiated directly.
Constructors Can have constructors. Cannot have constructors.
Method Implementation Can have both abstract and concrete methods. Can only declare abstract methods (no code).
Method Overriding Subclasses override methods as needed. Implementing classes must provide method bodies.
Inheritance Supports single-class inheritance. Supports multiple interface inheritance.
Fields and Constants Can have fields (instance variables). Can only have public, static, final fields (constants).
Default Methods (Java 8+) Cannot have default methods. Can have default methods with implementations.
Static Methods (Java 8+) Can have static methods. Can have static methods.
Multiple Inheritance (Java 8+) Does not support multiple inheritance. Supports multiple inheritance of method signatures.
Purpose Used for code reuse and common base classes.
Used for defining contracts and multiple inheritance of method
signatures.
When to Use
Use when there's a common implementation among
subclasses and when you want to provide a base class with
some default behavior.
Use when you want to define a contract for implementing
classes or when you need multiple inheritance of method
signatures.
Example abstract class Animal { ... } interface Drawable { ... }
Practice Questions
1. Write an abstract class Vehicle with an abstract method start() and a
concrete method stop(). Create a subclass Car that extends Vehicle and
provides implementations for the start() method
2. Design an abstract class Employee with fields name and salary. Create
two subclasses, Manager and Developer, that inherit from Employee.
Implement constructors for each subclass and override the toString()
method to display the details of the employees.
3. Write an abstract class BankAccount with fields for accountNumber and
balance. Declare an abstract method withdraw(double amount) and a
concrete method deposit(double amount). Create a subclass
SavingsAccount that extends BankAccount and implements the
withdraw() method to deduct a withdrawal fee.
4. Design an abstract class Animal with an abstract method makeSound().
Create two subclasses, Dog and Cat, that inherit from Animal and
implement the makeSound() method to produce appropriate animal
sounds.
Practice Questions
5. Create an interface Drawable with a method draw(). Implement the
interface in two classes, Circle and Rectangle, each providing its own
implementation of the draw() method.
6. Design an interface Eatable with a method eat(). Implement this interface
in a class Apple to describe how to eat an apple and in a class PizzaSlice to
describe how to eat a pizza slice
7. Design an interface Logger with a method log(String message). Implement
this interface in a class ConsoleLogger to print log messages to the console.
8. Define an interface Playable with methods play() and stop(). Implement the
Playable interface in a class MusicPlayer to play and stop music.

More Related Content

Similar to Abstraction in Java: Abstract class and Interfaces

Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programmingdeffa5
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#Sireesh K
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdfParvizMirzayev2
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078Aravind NC
 
Abstract_descrption
Abstract_descrptionAbstract_descrption
Abstract_descrptionMahi Mca
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxssuser84e52e
 
03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.ppt03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.pptJyothiAmpally
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 

Similar to Abstraction in Java: Abstract class and Interfaces (20)

Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Interface
InterfaceInterface
Interface
 
14 interface
14  interface14  interface
14 interface
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdf
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
 
Abstract_descrption
Abstract_descrptionAbstract_descrption
Abstract_descrption
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.ppt03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.ppt
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 

More from Jamsher bhanbhro

More from Jamsher bhanbhro (14)

Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In  JavaMethod, Constructor, Method Overloading, Method Overriding, Inheritance In  Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
 
Regular Expressions in Java.
Regular Expressions in Java.Regular Expressions in Java.
Regular Expressions in Java.
 
Java Arrays and DateTime Functions
Java Arrays and DateTime FunctionsJava Arrays and DateTime Functions
Java Arrays and DateTime Functions
 
Lect10
Lect10Lect10
Lect10
 
Lect9
Lect9Lect9
Lect9
 
Lect8
Lect8Lect8
Lect8
 
Lect7
Lect7Lect7
Lect7
 
Lect6
Lect6Lect6
Lect6
 
Lect5
Lect5Lect5
Lect5
 
Lect4
Lect4Lect4
Lect4
 
Compiling and understanding first program in java
Compiling and understanding first program in javaCompiling and understanding first program in java
Compiling and understanding first program in java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Caap presentation by me
Caap presentation by meCaap presentation by me
Caap presentation by me
 
Introduction to parts of Computer(Computer Fundamentals)
Introduction to parts of Computer(Computer Fundamentals)Introduction to parts of Computer(Computer Fundamentals)
Introduction to parts of Computer(Computer Fundamentals)
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 

Recently uploaded (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 

Abstraction in Java: Abstract class and Interfaces

  • 1. Abstract Class & Interface Object Oriented Programming By: Engr. Jamsher Bhanbhro Lecturer at Department of Computer Systems Engineering, Mehran University of Engineering & Technology Jamshoro 9/26/2023 Object Oriented Programming (22CSSECII)
  • 2. Books Recommendation Books Recommended 1. Head First Java by Kathy Sierra & Bert Bates. 2. Beginning Programming with Java For Dummies by Barry Burd 3. Java: Programming Basics for Absolute Beginners by Nathan Clark 4. Object Oriented Programming in Java by Rick Halterman Websites Recommended: DataFlair, Educative, course era
  • 3. Abstract Classes • A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body). Syntax public abstract class Shape{ public abstract void Draw( ); // Abstract method without definition public void Display( ) { System.out.println(“Display Method of Shape class”); } }
  • 4. Abstract & Non-Abstract Methods Abstract Methods • An abstract method is a method declared in an abstract class (or an interface) without providing a method body (i.e., without implementation). • It is declared using the abstract keyword. • Subclasses that extend the abstract class (or implement the interface) are required to provide an implementation for all abstract methods. If they don't, the subclass must also be declared as abstract. • Abstract methods define a contract that concrete subclasses must follow. abstract class Animal { public abstract void makeSound(); // Abstract //method with no implementation } Non-Abstract Methods • Non-Abstract Methods are Called Concrete Methods • A non-abstract method is a method that has a complete implementation in the class where it is declared. • Non-abstract methods have a method body containing code that defines their behavior. • Subclasses can inherit non-abstract methods as they are or override them to provide custom behavior. public void run() { System.out.println("The dog is running."); }
  • 5. Abstraction in Java • Abstraction is a process of hiding the implementation details and showing only functionality to the user. • Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery. • Abstraction lets you focus on what the object does instead of how it does it. Ways to achieve Abstraction • There are two ways to achieve abstraction in java • Abstract class (0 to 100%) • Interface (100%)
  • 6. Abstract Classes ➢A class must be declared abstract if any of the following condition is true − The class has one or more abstract methods − The class inherits one or more abstract methods for which it does not provide implementation − The class declares that it implements an interface but does not provide implementation for every method of that interface
  • 7. Abstract Classes ➢An abstract class cannot be instantiated / Object Can’t be created. − Abstract classes defer the implementation to subclasses − The subclass must provide the implementation of the abstract method or declare itself to be abstract in which case the implementation is deferred once again ➢You can declare a variable/reference of an abstract class.
  • 8. Abstract Class Example public abstract class LivingThing { public void breath( ){ System.out.println("Living Thing breathing..."); } public void eat( ){ System.out.println("Living Thing eating..."); } public abstract void walk( ); } public class Human extends LivingThing { public void walk( ){ System.out.println("Human walks..."); } } Public static void main(String args[]){ Human ob = new Human(); ob.walk(); ob.breath(); } }
  • 9. Abstract Class Example abstract class Shape{ abstract void draw(); } class Rectangle extends Shape{ void draw( ){ System.out.println("drawing rectangle"); } } class Circle1 extends Shape{ void draw( ){ System.out.println("drawing circle"); } } class TestAbstraction1{ public static void main(String args[]){ Shape s=new Circle1( ); s.draw( ); } } If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.
  • 10. Abstract Method in Abstract Class • An abstract method cannot be contained in a non-abstract class. • If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract. • In other words, in a non-abstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.
  • 11. Abstract Class //In Java It is possible to create abstract class without abstract methods too. abstract class Shape { private String color; // A non-abstract (concrete) method public void setColor(String color) { this.color = color; } // Another non-abstract method public String getColor() { return color;} // A constructor public Shape(String color) { this.color = color;} }
  • 12. An-other Example of Abstract Class abstract class Shape { // Abstract method (no implementation in the abstract class) public abstract double calculateArea(); // Concrete method (provides a default implementation) public void printDetails() { System.out.println("This is a shape."); } } class Rectangle extends Shape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } @Override public double calculateArea() { return length * width; } } class Circle extends Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double calculateArea() { return Math.PI * radius * radius; } public static void main(String[] args) { Circle circle = new Circle(5.0); Rectangle rectangle = new Rectangle(4.0, 6.0); // Calculate and print the areas double circleArea = circle.calculateArea(); System.out.println("Circle Area: " + circleArea); System.out.println("Rectangle Area: " + rectangle.calculateArea); circle.printDetails(); rectangle.printDetails(); } }
  • 13. Interface In Java • An interface is a blueprint for a set of methods that a class must implement. It defines a contract of method signatures that classes can adhere to, allowing for a common way to access related functionality across different classes and supporting multiple inheritance of method signatures. Essentially, an interface outlines what methods a class should provide without specifying how they are implemented. • Interfaces are used to achieve abstraction, provide a common way to access related functionality across different classes, and support multiple inheritance of method signatures. • Declaration: You define an interface using the interface keyword, followed by the interface's name and a list of method signatures.
  • 14. Interface In Java • Declaration interface MyInterface { void printName(); int add(int a, int b); } Methods: Interfaces can contain abstract method declarations. These methods do not have a method body (implementation). Any class that implements the interface must provide concrete implementations for all the methods declared in the interface. Constants: Interfaces can also contain constant declarations (fields) that are implicitly public, static, and final. These fields are typically used for defining constants that are relevant to the interface.
  • 15. Interface In Java • Implementing an Interface: To implement an interface, a class uses the implements keyword. A class can implement multiple interfaces. When a class implements an interface, it must provide concrete implementations for all the methods declared in the interface. class MyClass implements MyInterface { @Override public void printName() { System.out.println(“22CS MUET”); } @Override public add(int a, int b) { a+b; } }
  • 16. Interface Example public interface Shape { double calculateArea(); } class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } } class Rectangle implements Shape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } @Override public double calculateArea() { return length * width; } //create main method yourself }
  • 17. Abstract Vs Interface Feature Abstract Class Interface Syntax Declared using the abstract keyword. Declared using the interface keyword. Instantiation Cannot be instantiated directly. Cannot be instantiated directly. Constructors Can have constructors. Cannot have constructors. Method Implementation Can have both abstract and concrete methods. Can only declare abstract methods (no code). Method Overriding Subclasses override methods as needed. Implementing classes must provide method bodies. Inheritance Supports single-class inheritance. Supports multiple interface inheritance. Fields and Constants Can have fields (instance variables). Can only have public, static, final fields (constants). Default Methods (Java 8+) Cannot have default methods. Can have default methods with implementations. Static Methods (Java 8+) Can have static methods. Can have static methods. Multiple Inheritance (Java 8+) Does not support multiple inheritance. Supports multiple inheritance of method signatures. Purpose Used for code reuse and common base classes. Used for defining contracts and multiple inheritance of method signatures. When to Use Use when there's a common implementation among subclasses and when you want to provide a base class with some default behavior. Use when you want to define a contract for implementing classes or when you need multiple inheritance of method signatures. Example abstract class Animal { ... } interface Drawable { ... }
  • 18. Practice Questions 1. Write an abstract class Vehicle with an abstract method start() and a concrete method stop(). Create a subclass Car that extends Vehicle and provides implementations for the start() method 2. Design an abstract class Employee with fields name and salary. Create two subclasses, Manager and Developer, that inherit from Employee. Implement constructors for each subclass and override the toString() method to display the details of the employees. 3. Write an abstract class BankAccount with fields for accountNumber and balance. Declare an abstract method withdraw(double amount) and a concrete method deposit(double amount). Create a subclass SavingsAccount that extends BankAccount and implements the withdraw() method to deduct a withdrawal fee. 4. Design an abstract class Animal with an abstract method makeSound(). Create two subclasses, Dog and Cat, that inherit from Animal and implement the makeSound() method to produce appropriate animal sounds.
  • 19. Practice Questions 5. Create an interface Drawable with a method draw(). Implement the interface in two classes, Circle and Rectangle, each providing its own implementation of the draw() method. 6. Design an interface Eatable with a method eat(). Implement this interface in a class Apple to describe how to eat an apple and in a class PizzaSlice to describe how to eat a pizza slice 7. Design an interface Logger with a method log(String message). Implement this interface in a class ConsoleLogger to print log messages to the console. 8. Define an interface Playable with methods play() and stop(). Implement the Playable interface in a class MusicPlayer to play and stop music.