Click to editMaster title style
1
OOP: Lecture 09
Abstraction in Java
E n g r . A r i f H a s a n C h o w d h u r y, A s s i s t a n t P r o f e s s o r ,
D e p t . o f C S E , S o u t h e r n U n i v e r s i t y B a n g l a d e s h
E m a i l : a r i f h a s a n @ s o u t h e r n . a c . b d
2.
Click to editMaster title style
2
What is Abstraction in Java?
2
• Abstraction is the process of hiding certain details and showing only essential information to the user.
• hiding the implementation details from the user.
• User will have the information 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%)
3.
Click to editMaster title style
3
abstract class
3
class contains the abstract keyword in its declaration is
known as abstract class.
Abstract classes may or may not contain abstract
methods, i.e., methods without body ( public void
get(); )
if a class has at least one abstract method, then the
class mustbe declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from
another class, provide implementations to the abstract
methods in it.
If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
4.
Click to editMaster title style
4 4
Syntax and Example
Example
abstract class A
{
abstract void callme();
public void show()
{
System.out.println("this is non-abstract method");
}
}
class B extends A
{
void callme()
{
System.out.println("Calling...");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.show();
}
Output:
calling...
Syntax:
abstract class class_name {
Abstract Method
Non Abstact Method
}
5.
Click to editMaster title style
5
Example: abstact class with non abstract method
5
abstract class A
{
abstract void callme();
public void show()
{
System.out.println("this is non-abstract method");
}
}
class B extends A
{
void callme()
{
System.out.println("Calling...");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.show();
}
Output:
calling... this is non-abstract method
Abstraction using abstract class:
abstract class Vehicle
{
public abstract void engine();
}
public class Car extends Vehicle {
public void engine()
{
System.out.println("Car engine");
// car engine implementation
}
public static void main(String[] args)
{
Vehicle v = new Car();
v.engine();
}
}
Output:
Car engine
6.
Click to editMaster title style
6 6
• Can we create object of abstract class?