Pages

Abstraction

Encapsulation
Definition

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Advantages 1. We can reduces the complexity of viewing the things.
2. We can avoids code duplication and increases reusability.
3. We can Helps to increase security of an application or program as only important details are provided to the user.
Difference Between Abstraction and Encapsulation

Abstraction hides the implementation details whereas Encapsulation hides the data.

When We can use Abstract Class ? 1. You want to share code among several closely related classes.
2. You expect that classes that extend your abstract class have many common methods or fields or require access modifiers other than public such as protected and private.
3. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
When We can use Interface ? 1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
2. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
3. You want to take advantage of multiple inheritances.
Abstraction Example package com.jaladhi.jst;
public interface Car {
      void start();
      void stop();
}
package com.jaladhi.jst;
public class ManualCar implements Car {
      @Override
      public void start() {
            System.out.println("Start The Car");
      }
      @Override
      public void stop() {
            System.out.println("Stop The Car");
      }
}
package com.jaladhi.jst;
public class AutomaticCar implements Car {
      @Override
      public void start() {
            System.out.println("Start The Car");
      }
      @Override
      public void stop() {
            System.out.println("Stop The Car");
      }
}
public class TestCar {
      public static void main(String [] args) {
            System.out.println("Manual Car ");
            Car manual = new ManualCar();
            System.out.println("Automatic Car ");
            Car automatic = new AutomaticCar();
            manual.start();
            manual.stop();
            automatic.start();
            automatic.stop();
      }
}
Output :
Manual Car
Start The Car
Stop The Car
Automatic Car
Start The Car
Stop The Car