Thursday, June 17, 2021

Java OOPs: Abstraction

Chapters

Java Abstraction

Abstraction is the process of hiding intricate details of a system and only showing the essential parts. Operating System is an example of abstraction. When we use our computer, the operating system shows the user interface which users can interact with.

We don't need to know how the operating system creates the user interface in order to use it. When we open files, we don't need to know the mechanics of opening files in order to do that task and so on.

In java, we can achieve data abstraction by using abstract class or interface.
public class SampleClass{

  public static void main(String[]args){
  
    Windows win = new Windows();
    win.showUI();
    win.openFile();
    Linux linux = new Linux();
    linux.showUI();
    linux.openFile();
  }
}

interface OperatingSystem{

  void showUI();
  void openFile();
  
}

class Windows implements OperatingSystem{

  @Override
  public void showUI(){
    System.out.println("Showing Windows UI...");
    System.out.println("Task Done!");
  }
  @Override
  public void openFile(){
    System.out.println("Opening File Using Windows...");
    System.out.println("Task Done!");
  }
}

class Linux implements OperatingSystem{

  @Override
  public void showUI(){
    System.out.println("Showing Linux UI...");
    System.out.println("Operatiion Successful!");
  }
  
  @Override
  public void openFile(){
    System.out.println("Opening File Using Linux...");
    System.out.println("Operation Successful!");
  }
}
In the example above, we have two users(implementors), Windows and Linux. The users of the OperatingSystem interface ony need to know the method signatures. All other information about the overriden method in OperatingSystem interface is irrelevant.

Data abstraction increases the flexibility and simplicity of our source code.

No comments:

Post a Comment