Java: Abstraction and Encapsulation

Q. What is the difference between abstraction and encapsulation?

  • Abstraction solves the problem at design level while Encapsulation solves it implementation level.
  • In Java, Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected.
  • Abstraction is about hiding unwanted details while giving out most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect inner working of an object from outside world.
AbstractionEncapsulation
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Encapsulation is a process of wrapping code and data together into a single unit
Abstraction lets you focus on what the object does instead of how it does it. Encapsulation provides you the control over the data and keeping it safe from outside misuse.
Abstraction solves the problem in the Design Level. Encapsulation solves the problem in the Implementation Level.
Abstraction is implemented by using Interfaces and Abstract Classes. Encapsulation is implemented by using Access Modifiers (private, default, protected, public)
Abstraction means hiding implementation complexities by using interfaces and abstract class. Encapsulation means hiding data by using setters and getters.

Q. Can there be an abstract method without an abstract class?

Yes. because methods in an interface are also abstract. so the interface can be use to declare abstract method.

Q. Can we use private or protected member variables in an interface?

The java compiler adds public and abstract keywords before the interface method and public, static and final keyword before data members automatically

1
2
3
4
5
public interface Test {
public string name1;
private String email;
protected pass;
}

as you have declare variable in test interface with private and protected it will give error. if you do not specify the modifier the compiler will add public static final automatically.

1
2
3
4
5
public interface Test {
public static final string name1;
public static final String email;
public static final pass;
}

  • interfaces cannot be instantiated that is why the variable are static
  • interface are used to achieve the 100% abstraction there for the variable are final
  • An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them. that is why variable are public

Q. When can an object reference be cast to a Java interface reference?

An interface reference can point to any object of a class that implements this interface

interface Foo {
  void display();
}

public class TestFoo implements Foo {

    void display() {
      System.out.println("Hello World");
    }

    public static void main(String[] args) {
      Foo foo = new TestFoo();
      foo.display();
    }
}