In my presentation titled "Abstraction in Java," I have discussed the fundamental concept of abstraction in Java programming. The presentation delves into how abstraction is a key principle in object-oriented programming, explaining its role in hiding the complexity of code while exposing only the necessary details. It includes examples and explanations on implementing abstraction in Java, offering a clear understanding for both beginners and intermediate learners. This presentation serves as an educational guide for those interested in enhancing their Java programming skills and understanding the practical applications of abstraction in software development.
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.