Java Abstraction

Java Abstraction

Abstration is a feature of the OOP(object oriented programming). Abstarction is process of hiding the main details and showing only essential information or functionaltiy to user.

For the real-world example, if you want to stop the car you hit the brakes, but you don’t know what is actually happening inside the car and how it is possible to stop the car with brakes. this is an abstraction where user know how to use, but they don’t know how it works.

Abstract class in java

When a class is created with the prefix keyword abstract, it is called abstract class, for abstract class. the objects cant be instantiated.

To use abstract class,we can extend a subclass and we can instantiate objects and use the abstract class methods and its data members

The abstract class supports both the abstract method and nonabstact methods, static methods. we can use Abstract class constructer too.

Syntax

abstract class ClassName {
//attributes and methods
}

Example

abstract class absclass {
public void display() {
System.out.println("Abstract class");
}
public static void main(String[] args) {
absclass x = new absclass();
x.display();
}
}

Output

(Error)absclass.java:8: error: absclass is abstract; cannot be instantiated
absclass x = new absclass();
^

In the above program, we cannot create object to absclass, because that is a abstrcat class

Abstract Method in Java

abstract methods are created inside the Abstract class, Abstract methods should not be implemented ( there should no body for the abstract method ).

abstracted methods are created using the abstract keyword with normal method declaration.

Syntax

abstract return_type method();

there should be no body for method so,method declaration should end with ;

the abstract method should be overriden in the subclass to make it work. It is because the subclass inherits abstract methods of the parentclass.

Example

abstract class student {
abstract void study();
public void walk() {
System.out.println("I can walk.");
}
}
class boy extends student {
public void study() {
System.out.println("boy is studing");
}
}
class absclass {
public static void main(String[] args) {
boy b=new boy();
b.walk();
b.study();
}
}

Output

I can walk.
boy is studing

In the above example student class is an abstract class, so the abstract method study is declared inside the student class. a boy of the abstract method is written in the extended subclass called a boy. we have declared an object called b to the boy child class. and we can call walk( ) and study( ) from the b object

Last updated on by vishal devxo