Abstraction
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
Consider a real time example of booking a ride. When you book a ride using an app, you
select your destination, and the app shows available drivers. The app takes care of all the complex
stuff like tracking your location, finding the best driver, and providing real-time updates. presenting
a straightforward and user-friendly booking experience.
In Java Abstraction can be achieved using
1. abstract classes
2. Interfaces
Abstract Class In JAVA:
It is a restricted class that cannot be used to create objects. To access it, it must be
inherited from another class.
Rules for JAVA Abstract Class:
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Syntax of Abstract Classes in Java:
In Java, abstract classes are defined using the abstract keyword. Here's a basic syntax example:
public abstract class Shape
{
// Abstract method
public abstract double area();
// Concrete method
public void display()
{
System.out.println("This is a shape.");
}
}
In this example, Shape is an abstract class with one abstract method area() and one concrete
method display(). Subclasses of Shape must implement the area() method, but they can inherit the
display() method.
Syntax of Abstract Method in Java:
A method which is declared as abstract and does not have implementation is known as an abstract
method.
abstract void printStatus();
//no method body and abstract
Abstraction Example Program using Abstract method:
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal
{
public void animalSound()
{
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main
{
public static void main(String[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output:
The Pig says: Wee Wee
Zee
Explanation:
Let's walk through the provided Java program step by step:
Code Explanation:
1. Abstract Class: Animal
o The Animal class is an abstract class. Abstract classes cannot be instantiated
directly, and they may contain abstract methods (methods without a body) and
regular methods (methods with a body).
o Abstract Method animalSound(): This method is declared as abstract, which
means the class Animal does not provide a body for it. Any subclass of Animal must
provide its implementation for this method.
o Regular Method sleep(): This is a regular method, meaning it has a body. This
method prints "Zzz" when called.
2. Subclass: Pig
o The Pig class extends the Animal class. Since Pig is a subclass of Animal, it must
implement the abstract method animalSound() in order to be instantiated.
o Implemented animalSound() Method: The Pig class provides the implementation
for the animalSound() method, which prints the sound that a pig makes: "The pig
says: wee wee".
3. Main Class:
o The Main class contains the main method, which is the entry point for the program.
o Creating a Pig object: The Pig object myPig is created using the new keyword: Pig
myPig = new Pig();.
o Calling animalSound() and sleep() on myPig:
▪ myPig.animalSound(); invokes the animalSound() method of the Pig class,
which outputs: "The pig says: wee wee".
▪ myPig.sleep(); invokes the sleep() method inherited from the Animal class,
which outputs: "Zzz".
Program Output:
The pig says: wee wee
Zzz
Detailed Output Breakdown:
1. myPig.animalSound():
o The method animalSound() is called on the Pig object, which prints:
o The pig says: wee wee
2. myPig.sleep():
o The method sleep() is called on the Pig object. This method is inherited from the
abstract Animal class and prints: Zzz
Abstraction Using Interface in Java:
In Java, abstraction can also be achieved using interfaces. An interface is a reference type,
similar to a class, that can contain only abstract methods (methods without body) and constants. A
class implements an interface to provide the behavior for the abstract methods defined in the
interface.
• An interface can have abstract methods (without implementation) and default methods
(with implementation).
• A class that implements an interface must provide concrete implementations for all
abstract methods defined in the interface.
• A class can implement multiple interfaces, unlike inheritance with classes where only one
class can be extended.
1. we cannot extend two classes at once.
2. Interface is not a class, so it does not have any constructor, so we can implement multiple
interfaces for a same class.
3. we cannot create random variable, constant
4. By using default keyword, it takes reference for the concrete method
Multiple Inheritance in Java Using Interfaces
What is Multiple Inheritance?
• Multiple inheritance allows a class to inherit characteristics and behaviors from more than
one parent class. However, Java doesn't support multiple inheritance directly through
classes to avoid the complexity and ambiguity that arises from it (like the diamond
problem).
Using Interfaces to Achieve Multiple Inheritance:
• Instead of classes, Java uses interfaces to achieve multiple inheritance. A class can
implement multiple interfaces, thereby inheriting the abstract methods defined in those
interfaces.
Why Use Interfaces for Multiple Inheritance?
• Modularity: Interfaces help in breaking down large systems into smaller, manageable
components.
• Decoupling: They promote loose coupling by separating the definition of behavior from the
implementation.
• Flexibility: Implementing multiple interfaces allows a class to be flexible and reusable in
different contexts.
Abstraction Example Program using Interface:
// Defining an interface
interface Animal
{
// Abstract method (does not have a body)
void sound();
// Default method with a body
default void sleep()
{
System.out.println("This animal is sleeping.");
}
}
// Implementing the interface in a class
class Dog implements Animal
{
// Providing implementation for the abstract method sound()
public void sound()
{
System.out.println("Bark");
}
}
// Another class implementing the same interface
class Cat implements Animal
{
// Providing implementation for the abstract method sound()
public void sound()
{
System.out.println("Meow");
}
}
public class Main
{
public static void main(String[] args)
{
// Creating objects of Dog and Cat
Animal dog = new Dog();
Animal cat = new Cat();
// Calling methods using interface reference
dog.sound(); // Output: Bark
dog.sleep(); // Output: This animal is sleeping.
cat.sound(); // Output: Meow
cat.sleep(); // Output: This animal is sleeping.
}
}
Output:
Bark
This animal is sleeping.
Meow
This animal is sleeping.
Explanation:
1. Interface Animal:
o It defines one abstract method sound(), which must be implemented by any class
that implements this interface.
o It also defines a default method sleep() that provides a default behavior for all
implementing classes. The method prints "This animal is sleeping."
2. Class Dog and Class Cat:
o Both classes implement the Animal interface.
o Each class provides its own implementation of the sound() method (Dog barks and
Cat meows).
3. Main class:
o In the main() method, we create instances of Dog and Cat, both of which are
referred to by the Animal interface type.
o The sound() method of each class is called, displaying the specific sound for each
animal.
o The sleep() method is called, demonstrating the default behavior provided by the
interface.
Benefits of Using Interface for Abstraction:
• Loose coupling: The classes don't need to know about the implementation of methods in
other classes. They only depend on the interface.
• Multiple inheritance: A class can implement multiple interfaces, allowing greater flexibility
than single inheritance with classes.
• Default behavior: Interfaces can also provide default method implementations, making it
easier to add new methods without breaking existing implementations.
Abstract Class Interfaces
Abstract classes support abstract and Non- Interface in Java can have abstract methods,
abstract methods. default methods, and static methods.
Doesn’t support Multiple Inheritance. Supports Multiple Inheritance.
Abstract classes can be extended by Java classes The interface can be extended by Java interface
and multiple interfaces only.
Abstract Class Interfaces
Abstract class members in Java can be private,
Interfaces are public by default.
protected, etc.
Example: Example:
public abstract class Vehicle{ public interface Animal{
public abstract void drive() void speak();
} }
Encapsulation
Java Encapsulation is a way of hiding the implementation details of a class from outside access
and only exposing a public interface that can be used to interact with the class.
Encapsulation : It means wrapping up of code and data under a single unit. Ex : When we turn on
the Bluetooth we can assess only the shared content of the connected phone but not access to call
or send message from that phone.
Encapsulation Example Program:
// Java Program to demonstrate
// Java Encapsulation
// Person Class
class Person
{
// Encapsulating the name and age
// only approachable and used using
// methods defined
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
// Driver Class
public class Main
{
// main function
public static void main(String[] args)
{
// person object created
Person person = new Person();
person.setName("John");
person.setAge(30);
// Using methods to get the values from the
// variables
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Step-by-Step Execution
1. Creating the Person Object:
o The Person object person is instantiated with new Person().
o At this point, the name and age fields of the person object are initialized to their
default values:
▪ name is null (default value for an object reference).
▪ age is 0 (default value for an integer).
2. Setting Values:
o person.setName("John");: The setName method is called with the argument "John",
so the name field of the person object is updated to "John".
o person.setAge(30);: The setAge method is called with the argument 30, so the age
field of the person object is updated to 30.
3. Getting and Printing Values:
o System.out.println("Name: " + person.getName());: The getName() method is called,
which returns the current value of the name field, which is "John". The
System.out.println() method then prints Name: John to the console.
o System.out.println("Age: " + person.getAge());: The getAge() method is called, which
returns the current value of the age field, which is 30. The System.out.println()
method then prints Age: 30 to the console.
Output of the Program
When the program is executed, the output will be:
Name: John
Age: 30
This output is the result of the following actions:
1. The program sets the name field of the person object to "John".
2. The program sets the age field of the person object to 30.
3. The program then retrieves the values of name and age using the getter methods and prints
them to the console.
Difference between Abstraction and Encapsulation:
Encapsulation Abstraction
Encapsulation is data hiding(information Abstraction is detailed hiding(implementation
hiding) hiding).
Data Abstraction deals with exposing the
Encapsulation groups together data and
interface to the user and hiding the details of
methods that act upon the data
implementation
Encapsulated classes are Java classes that Implementation of abstraction is done using
follow data hiding and abstraction abstract classes and interface
Encapsulation is a procedure that takes place
abstraction is a design-level process
at the implementation level