You are on page 1of 33

Abstract Classes and

Interface in JAVA
Lecture 16 and 18

Instructor Name: Muhammad Fayyaz Awan


Department of Computer Science, COMSATS University Islamabad, Wah Campus, Pakistan
Outline
2

 What is an abstraction
 Ways to achieve abstraction
 Abstract class
 Interface
 Difference between abstract and interface
 References
Abstraction (1/7)
• Abstraction is a process by which concepts are derived from the
usage and classification of literal ("real" or "concrete") concepts.
• Abstraction is a concept that acts as a super-categorical noun for all
subordinate concepts, and connects any related concepts as a group,
field, or category.
• Abstractions may be formed by reducing the information content of a
concept or an observable phenomenon, typically to retain only
information which is relevant for a particular purpose.
• For example, abstracting a leather soccer ball to the more general
idea of a ball retains only the information on general ball attributes
and behavior, eliminating the other characteristics of that particular
ball.
Abstraction (2/7)
• Example Vehicle

• Here we have different types of truck and car.


They have different color, shape, engine type
and purpose etc. that makes them distinct.
• But they have some common properties and
behavior among them i.e. they all have tires,
engine, steering, gear etc. They are used for
the travelling and can be operated in a
common way. Pickup truck
Box truck
• What should be the abstract concept for
these entities?
Sports car Sedan car

• Vehicle can be the general idea of a car or a


truck. It retains only the information on general
vehicle attributes and behavior, eliminating the
other characteristics of a particular car or a
truck.
Abstraction (3/7)

Example Vehicle
• Here we have four classes Box truck, Classic
truck, Sports car and Sedan car.

• We can categorize them into two major


Truck Car
categories Truck and Car and can make
abstract classes which will contain all the
common properties and behaviors for trucks
and cars. Box truck Classic truck Sports car Sedan car

• We can further introduce abstraction for the


Truck and Car categories by adding a new
abstract class Vehicle that will hold common
properties and behaviors for its inheriting
classes.
Abstraction (4/7)

Example Animal

• Animal can be the


abstraction for a dog, tiger,
horse etc. It acts as a
super-categorical noun.

• As an abstract concept it can


hold all the common properties
and behaviors present in
different species Dog Tiger Horse
Abstraction (5/7)

• Here we have the abstract class Animal. Animal


We have defined color and pattern color
String
:

properties and sound, eat and run pattern : String


sound()
behaviors which are present in all eat()
run()
animals.

• The behaviors/ methods can be abstract


and the implementation can be
provided in the inheriting classes. Dog Tiger Horse
sound() sound() sound()
attack()
• Now we have three concrete classes guard()

inheriting from the Animal class.


Overriding the sound behavior and
adding some behaviors specific to the
entities.
Abstraction (6/7)
Aircraft

Example
• Aircraft can be the
abstraction for a Propeller
plane, Fighter plane,
Passenger plane etc. It acts
as a super-categorical
noun.

• As an abstract concept it
Propeller plane Fighter plane Passenger plane
can hold all the common
properties and behaviors
present in different aircrafts.
Abstraction (7/7)
Aircraft
Example color :
String engine :
Object
start()
• Here we have the abstract class Aircraft. We stop()
have defined color and engine properties and takeOff()
land()
start, stop takeOff and land behaviors which
are present in all Aircrafts.

• Now we have three concrete classes inheriting


from the Aircraft abstract class. We have added Propeller plane Fighter plane Passenger plane
some more properties and behaviors specific to propellers : int weapon : Object passengers : int
the entities. start() start() start()
stop() stop() stop()
takeOff() takeOff() takeOff()
• For example in Propeller plane the number of land() land() land()
fire()
propellers, in Fighter plane the weapon and
the fire behavior.
Ways to achieve abstraction

There are two ways to achieve abstraction in java.

1. Abstract class (0 to 100%)

2. Interface (100%)
1. Abstract class

•An abstract class must be declared with an abstract keyword.

•It can have abstract and non-abstract methods.

•It cannot be instantiated.

•It can have constructors and static methods also.

•It can have final methods which will force the subclass not to change the body
of the method.
Abstract class

Bank Account

Example owner : String


balance : Dollar

deposit(amount : Dollar)
• Here we have two classes withdraw(amount : Dollar)

Checking Account and Saving


Account.

• What are the common Checking Account Saving Account


properties and behavior owner : String
balance : Dollar
owner : String
balance : Dollar
between them? And what can insufficientFund
sFee : Dollar
annualInterestR
ate :
be the abstract class for these deposit(amount : Dollar)
Percentage

processCheck(checkToProcess : Check) deposit(amount : Dollar)


entities? withdraw(amount : Dollar) depositMonthlyInterest()
withdraw(amount : Dollar)
Abstract class (syntax)

abstract class Bike

Bike() //constructor
{}
abstract void run(); //abstract method

void changeGear() //non-abstract method


{} 
 }  
Abstract class (Example with code)
abstract class Bike{  private int speed=70;
Bike(){System.out.println("bike is created");}  
abstract void run();  
void changeGear()
{System.out.println("gear changed");}   //main method
}   public static void main(String args[])
{  
//Creating a Child class which inherits Abstract 
Bike obj = new Honda();  
class   obj.run();  
class Honda extends Bike{   obj.changeGear();  
}   
void run(){System.out.println("running safely..");
System.out.println(speed);}  
}  
Abstract class (Example explanation)

• An abstract class can have a data member, abstract method,


method body (non-abstract method), constructor, and even
main() method.

• Its implementation is provided by the Honda class.


When to use abstract class?

• Abstract class provides a template for future specific classes.


• Use an abstract class to provide default behaviors (Code reusability).
• Abstract class defines common interface for its subclasses.
• Abstract operations (methods) can be declared and their implementation can be provided later
in the concrete classes.
• Abstract classes are useful when creating components because they allow us to specify an invariant
level of functionality in some methods, but leave the implementation of other methods until a specific
implementation of that class is needed.
• When creating a class library which will be widely distributed or reused especially to clients, use an
abstract class in preference to an interface; because it simplifies versioning. This is the practice used by
the Microsoft team which developed the Base Class Library.
2. Interface

• These are all mammals and share some


common behavior and properties. Like they
are warm blooded, they can have fur or hair,
they nourish their young with milk etc.
Mammals
• Bat has a special behavior i.e. that it can fly.
Flying is the behavior which is only available
Example: in Bat and not in other mammal.
• Birds can also fly.

• The Bat and Bird belongs to two different


categories but they have a common flying Can fly
behavior between them.
• In this scenario we can create an IFlyable
interface and make the Bat and Bird class
implement this interface.

Birds
Interface
<<IWritable>>
Example
draw()

• Fountain pen and ball point pen are


used for writings, they are related
entities. What should be the Pen
abstract class for these entities? color : String
draw()

• We can write using pen but we can


also write with charcoal. Over here
what is the common behavior Charcoal Ball point pen Fountain pen
between pen and charcoal that can burn() draw() draw()

be abstracted? draw() refill()

Person
write(IWritable : instrument)
Interface
• An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

• The interface in Java is a mechanism to achieve abstraction.

• There can be only abstract methods in the Java interface, not method body.

• It is used to achieve abstraction and multiple inheritance in java.

• In other words, you can say that interfaces can have abstract methods and
variables.

• It cannot have a method body.

• Java Interface also represents the IS-A relationship.


How to declare an interface?

An interface is declared by using the interface keyword. It provides total


abstraction.

It means all the methods in an interface are declared with the empty body, and
all the fields are public, static and final by default.

A class that implements an interface must implement all the methods declared
in the interface.
Interface (Syntax)

interface abc
{        
  // declare constant fields  
   // declare methods that abstract   
   // by default.  
}  

Interface fields are public, static and final by default, and the
methods are public and abstract.
Relationship b/w classes and interfaces

As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
Interface (Example with code)
//Interface declaration: by first user  
interface Drawable
{  
void draw();  
}   //Main method
//Implementation: by second user   public static void main(String args[])
class Rectangle implements Drawable {  
{   Drawable d=new Circle; 
public void draw() d.draw();  
{System.out.println("drawing rectangle");}   }  
}  
class Circle implements Drawable
{  
public void draw()
{System.out.println("drawing circle");}  
}  
Interface (Example explanation)

In this example, the Drawable interface has only one method.

Its implementation is provided by Rectangle and Circle classes.

In a real scenario, an interface is defined by someone else, but its implementation


is provided by different implementation providers.

Moreover, it is used by someone else.

The implementation part is hidden by the user who uses the interface.
When to use Interface?

• Use an interface when an immutable contract is really


intended.

• Interfaces are better suited in situations when your applications


require many possibly unrelated object types to provide certain
functionality.

• Interfaces are better in situations in which you do not


need to inherit implementation from a base class.

• Interfaces can be used for multiple inheritance.


Another real scenario of abstract class and interface

• The abstract class can also be used to provide some implementation


of the interface.

• In such case, the end user may not be forced to override all the
methods of the interface.
Example
interface A
{  
void a();  
void b();  
void c();   //Main method 
void d();   public static void main(String args[])
}     {  
abstract class B implements A A a=new M();  
{ a.a();  
public void c() {System.out.println("I am c");}   a.b();  
} a.c();  
     a.d();  
class M extends B }  
{  
public void a() {System.out.println("I am a");}  
public void b() {System.out.println("I am b");}  
public void d() {System.out.println("I am d");}  
}  
Conclusion of abstract class and interface
(important point)
• Abstract class is a concept and implementation gets completed when it is being realized
by a subclass.

• Abstract classes provide elements of both inheritance and interfaces (see example on
previous slide).

• An abstract class is a class that cannot be instantiated itself; it must be inherited.

• Some or all members of the class might be unimplemented, and it is up to the inheriting
class to provide that implementation.

• Members that are implemented might still be overridden, and the inheriting class can still
implement additional interfaces or other functionality.
Difference between abstract class and interface
Feature Interface Abstract class
Multiple Inheritance A class may implement several A class may inherit only one
interfaces. abstract class.
Default An interface is purely abstract, it cannot An abstract class can provide
implementation provide any code, just the signature. complete, default code and/or
just the details that have to be
overridden.
Access modifiers An interface cannot have access modifiers An abstract class can contain
for the method, properties etc. Everything access modifiers for the
is assumed as public. methods, properties etc.
Core vs. Peripheral Interfaces are used to define the An abstract class defines the
peripheral abilities of a class. In other core identity of a class and there
words both Human and Vehicle can inherit it is used for related objects.
from a IMovable interface.
Homogeneity If various implementations only share If various implementations are of
method signatures then it is better to use the same kind and use common
Interfaces. behavior or status then abstract
class is better to use.
Difference between abstract class and interface

Feature Interface Abstract class

Adding functionality If we add a new method to an If we add a new method to an


(Versioning) Interface then we have to track abstract class then we have
down all the implementations of the the option of providing default
interface and define implementation implementation and therefore
for the new method. all the existing code might
work properly.

Fields and Constants No fields can be defined in interfaces An abstract class can have
fields and constants defined
“is-a” and "can-do" analogy

• Abstract classes are classes that can be purely abstract.


• It serves as a base for other classes. When a class is derived from a base
class, that derived class has an "is-a" relationship with the base.
• For example an Employee is a person and a Triangle is a shape so these
cases could easily justify a base class and “is-a” relationship.
• Interfaces are purely abstract and guarantee member invariance. They
represent "can-do" or an invariant contract that specifies "can do and
will always do as expected to do“.
• Its appropriate to use an interface when it will be used by many,
unrelated types or in situations when multiple inheritance is
required.
References
32

• https://www.javatpoint.com/abstract-class-in-java
• https://www.geeksforgeeks.org/abstract-classes-in-java/?ref=lbp
33

THANK YOU

You might also like