Abstraction
Abstraction
What is Abstraction?
• Abstraction is a process where you show only “relevant”
data and “hide” unnecessary details of an object from the
user.
• It is a process of hiding the implementation details from
the user and showing only functionality to the user.
• In other words, the user will have the information on what
the object does instead of how it does it.
What is Abstraction? Example
• Example: For example, when you consider the case of e-
mail, complex details such as what happens as soon as you
send an e-mail, the protocol your e-mail server uses are
hidden from the user. Therefore, to send an e-mail you just
need to type the content, mention the address of the
receiver, and click send.
What is Abstraction in Java?
(Example)
• Example: Consider a real-life example of a man driving a
car. The man only knows that pressing the accelerators
will increase the speed of a car or applying brakes will
stop the car, but he does not know about how on pressing
the accelerator the speed is actually increasing, he does
not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car.
This is what abstraction is.
How abstraction is achieved?
• It is achieved by the use of Abstract classes and
Interfaces.
Abstract classes
• Java allows abstract classes
• use the modifier abstract on a class header to declare an abstract
class
abstract class Pet
{ … }
• An abstract class is a placeholder
Pet
in a class hierarchy that
represents a generic concept.
Cat Cog
Abstract class: Example
Abstract class: Example
• An abstract class often contains abstract methods and concrete methods
• Abstract methods consist of only methods declarations, without any method body
abstract class Pet {
Pet() {
System.out.println("Pet Cons...");
}//default cons
}//class
Abstract classes: Salient points
• 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.
• It can have final methods which will force the subclass not to change the body of the
method.
• If a class has an abstract method, the class needs to be abstract.
• An abstract class must contain atleast one abstract method.
• The subclass can extend ONLY ONE abstract class.
• The non-abstract child of an abstract class must override the abstract methods of the
parent.
Abstraction using Interfaces
• Interfaces are similar to abstract classes but differ in functionality.
• Interfaces syntactically similar to classes, but they lack instance variables
and their methods are without any body.
• Interfaces can have final variables, which must be initialized.
• Interfaces are used to achieve 100% abstraction.
• Interfaces cannot have concrete methods and non-final variables.
• Methods are abstract by default.
• All methods are automatically public.
• The subclass can implement more than ONE Interface.
Interface Example
Any Questions?