Loading

Q1. What is abstraction in Java, and why is it used?

Abstraction is the process of hiding implementation details and showing only the essential features to the user.
It is used to reduce complexity, increase code reusability, and achieve loose coupling.
In Java, abstraction is achieved using abstract classes and interfaces.


Q2. What is the difference between an abstract class and an interface?
  • Abstract Class: Can have both abstract (unimplemented) and concrete (implemented) methods. Supports fields, constructors, and method definitions.
  • Interface: Contains only abstract methods (until Java 7). From Java 8 onward, it can also have default and static methods. Multiple interfaces can be implemented by a class (supports multiple inheritance).

Q3. Can we create an object of an abstract class in Java? Why or why not?

No, we cannot create an object of an abstract class.
Reason: An abstract class may have unimplemented methods, so Java prevents instantiation. Instead, we create an object of a subclass that provides implementations for all abstract methods.


Q4. How does abstraction differ from encapsulation?
  • Abstraction: Focuses on hiding implementation details (what to do, not how). Achieved via abstract classes/interfaces.
  • Encapsulation: Focuses on hiding data using access modifiers (private, public, etc.) and exposing via getters/setters.

Q5. Give a real-world example of abstraction in Java.
When you drive a car, you use the steering, brake, accelerator but you don not know the internal engine mechanism.

In Java:

abstract class Vehicle {

   abstract void start();

}


class Car extends Vehicle {

   void start() {

      System.out.println("Car starts with a key");

   }

}