Friday, March 31, 2023

Abstraction in Java with Examples

Abstraction is a crucial concept in object-oriented programming, enabling developers to concentrate on an object's essential aspects and behavior, rather than implementation specifics. interfaces and abstract classes are used to implement Abstraction in Java, offering a means to define shared behaviors and properties for classes that have a similar purpose or functionality. This article will delve into the notion of abstraction in Java, providing practical examples to showcase its application.


Abstraction in Java


Abstraction in Java

What is Abstraction in Java?

  1. Abstraction is a process of hiding details about implementation from the user while letting them utilize the services or functions.
  2. Exposing only required or important things is called abstraction.
  3. It is used for maintaining the standards of coding in project.

Don't get Confused between Abstraction and Encapsulation.

Abstraction

Encapsulation

Abstraction is a detail hiding(implementation hiding). Encapsulation is data hiding(information hiding).
Data abstraction deals with exposing the interface to the user and hiding the details of implementation. Encapsulation groups together data and methods that act upon the data.

Real-time Example of Abstraction in Java.

As in the car case, relevant parts like staring, gear, breaks etc. are shown to driver because they are necessary for driving. But the driver need not know the internal functioning of gear, breaks etc. Thus, Showing relevant data to the user and hiding the implementation of details from the user is Abstraction.

Real-time Example of Abstraction in Java.


How to Achieve Abstraction in Java?

Abstraction can be Achieved by two ways :
  1. Interfaces
  2. Abstract classes
Abstraction can be Achieved by two ways


Interface

Interfaces are an important feature of Java that provide a way to define contracts between classes and promote abstraction, polymorphism, and loose coupling. By using interfaces, we can write more modular and flexible programs that can be easily extended and maintained.

Interface in Java



What is an Interface in Java?

  • An interface in Java is a blueprint of a class. It specify what a class must do and not.
  • The interface in Java is a Way to achieve 100%  abstraction.
  • Only abstract methods allowed in the Java interface, not a method body.
  • Variables are public final static in interface and act like constants.
  • Since Java 8, we have default and static methods in the interface.
  • Since Java 9, we have private methods in the interface.
  • Interface can be compiled but cannot run.
  • The interface doesn't have a constructor.
  • We cannot instantiate Interface but we can create reference variables.

Why we use Interface in Java?

  1. It is used to achieve abstraction.
  2. By interface, we can support the functionality of multiple inheritance.
  3. It can be used to achieve loose coupling.

Syntax of Interface in Java 


[access_modifier] interface InterfaceName  { 
// constant declarations 
public static final datatype CONSTANT_NAME = value; 
// method declarations
public abstract return_type methodName([parameter_list]); 
// default method
[access_modifier] default return_type methodName([parameter_list]) { 
// method body 
 } 
// static method 
[access_modifier] static return_type methodName([parameter_list]) {
// method body 
 } 
// private method (Java 9 onwards) 
[access_modifier] private return_type methodName([parameter_list]) { 
// method body 
 } 
}
  1. access_modifier: Optional keyword that specifies the access level of the interface or its members. Can be public, protected, or private. If no access modifier is specified, the default is public.
  2. interface: Keyword that indicates the declaration of an interface.
  3. InterfaceName: Name of the interface.
  4. constant declarations: Optional declarations of constant variables. These variables are implicitly public, static, and final.
  5. method declarations: Declarations of methods that are implemented by the classes that implement the interface. These methods are implicitly public and abstract.
  6. default method: A method that provides a default implementation in the interface itself. Introduced in Java 8.
  7. static method: A method that is associated with the interface and can be called without an instance of the implementing class. Introduced in Java 8.
  8. private method: A method that is used only within the interface itself and cannot be accessed by any implementing classes. Introduced in Java 9.

The Relationship Between Classes and Interfaces

  1. interface can extend interface1 and interface2 ...
  2. class extends class implements interface
  3. class implements interface
  4. class extends class implements interface1 and interface2 ...

Example of Interface in Java



// Define an interface 
interface Shape { 
// Declare abstract methods 
void draw()
double getArea(); } 
// Implement the interface in a class 
class Rectangle implements Shape { 
private double length; 
private double width; 
// Constructor to initialize fields 
public Rectangle(double length, double width)
this.length = length; 
this.width = width; 
 } 
// Implement the abstract methods 
public void draw()
 System.out.println("Drawing a rectangle"); 
 } 
public double getArea()
return length * width; 
 } 
// Create an instance of the Rectangle class 
public class Main
public static void main(String[] args) {
 Rectangle rect = new Rectangle(5, 10); 
 rect.draw(); 
// Output: "Drawing a rectangle" 
 System.out.println("Area of the rectangle: " + rect.getArea()); 
// Output: "Area of the rectangle: 50.0" 
 } 
}

In this example, we define an interface Shape with two abstract methods: draw() and getArea(). We then create a class Rectangle that implements the Shape interface and provides an implementation for the abstract methods. Finally, we create an instance of the Rectangle class and call its methods to draw the rectangle and calculate its area. By using the interface, we can easily add new shapes to our program and ensure that they all have the necessary methods to function correctly.

Abstract classes

Abstract class in Java is a class that cannot be instantiated on its own, but can be subclassed by other classes. Abstract classes are used to define a common interface for a set of subclasses, while allowing subclasses to provide specific implementations of methods and variables.

Abstract classes in Java



What is Abstract Class in Java?

  • A class which is declared as abstract is known as an abstract class.
  • It can have abstract and non-abstract methods. 
  • It needs to be extended and its method implemented.
  • We cannot instantiate abstract class.
  • Abstract class can have constructor.
  • Multiple inheritances are not allowed in abstract class.

Why we use Abstract Class in Java?

  1. To define a template for a group of related classes: An abstract class can provide a template or a blueprint for a set of related classes, defining the common properties and behavior that they share.
  2. To implement some methods in a superclass: Abstract classes can have both abstract and non-abstract methods. We can use abstract classes to implement some common methods in a superclass, while leaving other methods to be implemented in subclasses.
  3. To achieve abstraction: An abstract class can be used to achieve abstraction, which is the process of hiding the implementation details of a method or variable from the user, and exposing only the necessary information.

Syntax of Abstract Class in Java 



abstract class ClassName { // variables and methods }

An abstract class can have variables and methods, just like a regular class. However, it may also have abstract methods, which do not have an implementation.

Example of Abstract Class in Java



// abstract class 
abstract class Animal
// instance variables 
String name; 
int age; 
// constructor 
public Animal(String name, int age)
this.name = name; 
this.age = age; 
 } 
// abstract method 
public abstract void makeSound()
// non-abstract method 
public void printDetails()
 System.out.println("Name: " + name);
 System.out.println("Age: " + age); 
 } 
// subclass of abstract class 
class Dog extends Animal
// constructor
public Dog(String name, int age)
 super(name, age); 
 } 
// implementation of abstract method 
public void makeSound()
 System.out.println("Woof!"); 
 } 
// main class 
public class Main
public static void main(String[] args)
// create an instance of Dog class 
 Dog myDog = new Dog("Buddy", 3); 
// call methods on Dog object 
 myDog.makeSound(); myDog.printDetails();
 }
 }


In this example, Animal is an abstract class that has two instance variables name and age, a constructor that initializes these variables, an abstract method makeSound(), and a non-abstract method printDetails().

The Dog class extends the Animal class and provides an implementation for the makeSound() method.

In the Main class, we create an instance of the Dog class and call the makeSound() and printDetails() methods on it.

Note that we cannot create an instance of the abstract Animal class itself, but we can create instances of its subclasses like Dog.


Conclusion

Abstraction is an essential concept in Java and object-oriented programming. It allows developers to define common behaviors and properties for classes that share a similar purpose or functionality, without worrying about implementation details. Interfaces and abstract classes provide a way to achieve abstraction in Java, by defining contracts that classes must follow and providing partial implementations for classes to extend.

You Know?

1.When to Use Abstract Class and Interface in Java?

Use an abstract class when:
  1. You want to provide a common implementation or default behavior for a group of related classes.
  2. You want to define non-static or non-final fields that subclasses can inherit.
  3. You want to provide constructors that subclasses can call.
  4. You want to define non-public or non-abstract methods that subclasses can call.

Use an interface when:
  1. You want to define a contract or set of behaviors that a class must implement.
  2. You want to support multiple inheritance of type, where a class can implement multiple interfaces but extend only one class.
  3. You want to create a loosely-coupled design, where a class can interact with other classes without knowing their implementation details.

2.Difference Between Abstract Class and Interface.

Abstract Class

Interface

Abstract Class Contains both abstract and non-abstract methods. Interface Contains only abstract methods.
Since Java 8, it can have default and static methods also.
Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
A abstract class can have class members like private, protected, etc. Members of a interface are public by default.td>
Abstract class achieves partial abstraction (0 to 100%). Interface achieves fully abstraction (100%).
The abstract class have a constructor. The interface doesn't have a constructor.

3.Why abstraction is used in Java?

Abstraction is a crucial concept in Java programming that enables developers to hide the complexity of the code from end-users. By reducing the project's features to only the essential components, data abstraction in Java ensures that end-users only interact with what is necessary, making the code easier to understand and use.

4.What are Unique Uses of Abstraction?

  1. Hiding useless information.
  2. Generalizing a concept.
  3. Dealing with an idea representing the reality.

5.Why not constructor in Interface?

In interface it will not get called by using super by using hierarchy

6. As an interface has abstract method, how will you use the abstract method of interface?

Implement that method in class, or in other words override methods, and then create object of that class and call all methods.

7.Why does the abstract class have a constructor even though you cannot create object?

Abstract class can only be extended by class and that class will have its own constructor and that constructor will have super (); which is calling constructor of abstract class. If the abstract class doesn't have constructor then the class extending that abstract class will not get compiled. Therefore, abstract classes have constructors.

8.If abstract class can have both types of methods [one having body and other without body] then what is use of those methods?

We can use those methods by (1) extending abstract class or (2) making that method as a static so that we will not need to create an object.

9.What is Abstract Method in Java?

A method which is declared as abstract and does not have implementation is known as an abstract method.



No comments:

Post a Comment