Data Abstraction in Java

Data abstraction is hiding the implementation of a work or method. i.e showing only what is done and hiding how it is done.

For example, if you are sending a text message to a friend, you can know only the message is sent or not. You can't get how it is sent.

This is generally achieved using

  • abstract class
  • interfaces

Abstract class

A class which is given as abstract is known as abstract class.

abstract class classname{

//fields or methods

}

Example

abstract class MilitarySecrets{

int total;

void total_equipments(int guns,int missiles,int jets){

total=guns+missiles+jets;

}

}

class Military extends MilitarySecrets{

void power(int guns,int missiles,int jets){

total_equipments(guns,missiles,jets);

}

void ispowerful(){

if(super.total>200)

System.out.print("This military is powerful");

else

System.out.print("This military is not powerful");

}

}

class MainService{

public static void main(String args[]){

Military india=new Military();

india.power(100,50,100);

india.ispowerful();

}

}

Try In Editor

Output

This military is powerful


We cannot create objects for an abstract class, we can only extend or inherit abstract class.


Abstract method

If you want to just declare a method in a class and implement the method in a child class, we can use abstract method.

Methods prefixed with abstract keyword is known as abstract method.

The class of the abstract method must be abstract to use abstract method.

Example

abstract void ispowerful();

Full program

abstract class MilitarySecrets{

int total;

void total_equipments(int guns,int missiles,int jets){

total=guns+missiles+jets;

}

abstract void ispowerful();

}

class Military extends MilitarySecrets{

void power(int guns,int missiles,int jets){

total_equipments(guns,missiles,jets);

}

void ispowerful(){

if(super.total>200)

System.out.print("This military is powerful");

else

System.out.print("This military is not powerful");

}

}

class MainService2{

public static void main(String args[]){

Military india=new Military();

india.power(100,50,100);

india.ispowerful();

}

}

Try In Editor

Output

This military is powerful