Abstraction in Java
Abstraction in Java
Abstraction in Java
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
Advantages of Abstraction
Abstract Modifier:
Abstract is the modifier applicable only for methods and classes but not for
variables.
Abstract class:
For any java class if we are not allow to create an object such type of class we have
to declare with abstract modifier that is for abstract class instantiation is not
possible.
abstract class A{
}
It can have abstract and non-abstract methods.
It cannot be instantiated.
Example:
Abstract Methods:
Ex:
Class Test{
System.out.println(“providing implementation”);//invalid
Child classes are responsible to provide implementation for parent class abstract
methods.
Ex:
Ex-2:-
File: TestBank.java
Diagram:
All the 6 combinations are illegal
Abstract class:
For any java class if we are not allow to create an object such type of class we have
to declare with abstract modifier that is for abstract class instantiation is not
possible.
Example:
}}
Output:
D:\Java>javac Test.java
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
File: TestAbstraction2.java
Ex:-
class Bike{
abstract void run();
}
Output:
Compile time error.
Example2:
class Parent{
Output:
D:\Java>javac Parent.java
Example3:
class Parent{
Output:
Example3:
class Parent{
Output:
D:\Java>javac Parent.java
Parent.java:1: Parent is not abstract and does not override abstract method
methodOne() in Parent
class Parent
Note: If a class extends any abstract class then compulsory we should provide
implementation for every abstract method of the parent class otherwise we have to
declare child class as abstract.
Example:
If we declare class child as abstract then the code compiles fine but child of child is
responsible to provide implementation for m2().