Abtraction

Data Abstraction is the property by virtue of which only the essential details are exhibited to the user. The trivial or the non-essentials units aren’t exhibited to the user. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

Example: Consider a real-life scenario of withdrawing money from ATM. The user only knows that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount which he/she wants to withdraw and at last, he/she gets their money. The user does not know about the inner mechanism of the ATM or the implementation of withdrawing money etc. The user just simply knows how to operate the ATM machine, this is called abstraction.

In C# abstraction is achieved with the help of Abstract classes and Access modifiers

Abstract Classes

  • An abstract class is declared with the help of abstract keyword.

  • In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstract class directly with the new operator.

  • Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract Base Class.

  • Class that contains the abstract keyword with all of its methods is known as pure Abstract Base Class.

  • You are not allowed to declare the abstract methods outside the abstract class.

  • You are not allowed to declare an abstract class as Sealed Class.

  • You are not allowed to declare an abstract class as Static Class.

Using abstract classes and abstract methods with an example

There are situations in which we want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on – each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a square.

Example:

// C# program to calculate the area
// of a square using the concept of
// data abstraction
using System;

namespace Demoabstraction {
	
// abstract class
abstract class Shape {

	// abstract method
	public abstract int area();
}

// square class inheriting
// the Shape class
class Square : Shape {

	// private data member
	private int side;

	// method of square class
	public Square(int x = 0)
	{
		side = x;
	}
	
	// overriding of the abstract method of Shape
	// class using the override keyword
	public override int area()
	{
		Console.Write("Area of Square: ");
		return (side * side);
	}
}

// Driver Class
class GFG {
	
	// Main Method
	static void Main(string[] args)
	{
		
		// creating reference of Shape class
		// which refer to Square class instance
		Shape sh = new Square(4);
		
		// calling the method
		double result = sh.area();
		
		Console.Write("{0}", result);

	}
}
}

Output:

Area of Square: 16

Java Abstract classes and Java Abstract methods

  1. An abstract class is a class that is declared with an abstract keyword.

  2. An abstract method is a method that is declared without implementation.

  3. An abstract class may or may not have all abstract methods. Some of them can be concrete methods

  4. A method-defined abstract must always be redefined in the subclass, thus making overriding compulsory or making the subclass itself abstract.

  5. Any class that contains one or more abstract methods must also be declared with an abstract keyword.

  6. There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.

  7. An abstract class can have parameterized constructors and the default constructor is always present in an abstract class.

Algorithm to implement abstraction in Java

  1. Determine the classes or interfaces that will be part of the abstraction.

  2. Create an abstract class or interface that defines the common behaviors and properties of these classes.

  3. Define abstract methods within the abstract class or interface that do not have any implementation details.

  4. Implement concrete classes that extend the abstract class or implement the interface.

  5. Override the abstract methods in the concrete classes to provide their specific implementations.

  6. Use the concrete classes to implement the program logic.

When to use abstract classes and abstract methods in Java

There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. Sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size, and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on — each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes.

// Java program to illustrate the
// concept of Abstraction
abstract class Shape {
	String color;

	// these are abstract methods
	abstract double area();
	public abstract String toString();

	// abstract class can have the constructor
	public Shape(String color)
	{
		System.out.println("Shape constructor called");
		this.color = color;
	}

	// this is a concrete method
	public String getColor() { return color; }
}
class Circle extends Shape {
	double radius;

	public Circle(String color, double radius)
	{

		// calling Shape constructor
		super(color);
		System.out.println("Circle constructor called");
		this.radius = radius;
	}

	@Override double area()
	{
		return Math.PI * Math.pow(radius, 2);
	}

	@Override public String toString()
	{
		return "Circle color is " + super.getColor()
			+ "and area is : " + area();
	}
}
class Rectangle extends Shape {

	double length;
	double width;

	public Rectangle(String color, double length,
					double width)
	{
		// calling Shape constructor
		super(color);
		System.out.println("Rectangle constructor called");
		this.length = length;
		this.width = width;
	}

	@Override double area() { return length * width; }

	@Override public String toString()
	{
		return "Rectangle color is " + super.getColor()
			+ "and area is : " + area();
	}
}
public class Test {
	public static void main(String[] args)
	{
		Shape s1 = new Circle("Red", 2.2);
		Shape s2 = new Rectangle("Yellow", 2, 4);

		System.out.println(s1.toString());
		System.out.println(s2.toString());
	}
}

Output

Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0

Here are some reasons why we use abstract:

1. Abstraction:

Abstract classes are used to define a generic template for other classes to follow. They define a set of rules and guidelines that their subclasses must follow. By providing an abstract class, we can ensure that the classes that extend it have a consistent structure and behavior. This makes the code more organized and easier to maintain.

3. Polymorphism:

Abstract classes and methods enable polymorphism. Polymorphism is the ability of an object to take on many forms. This means that a variable of an abstract type can hold objects of any concrete subclass of that abstract class. This makes the code more flexible and adaptable to different situations.

3. Frameworks and APIs:

Java has numerous frameworks and APIs that use abstract classes. By using abstract classes developers can save time and effort by building on existing code and focusing on the aspects specific to their applications.

In summary, the abstract keyword is used to provide a generic template for other classes to follow. It is used to enforce consistency, inheritance, polymorphism, and encapsulation.

Encapsulation vs Data Abstraction

  1. Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding).

  2. While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation.

  3. Encapsulated classes are Java classes that follow data hiding and abstraction We can implement abstraction by using abstract classes and interfaces.

  4. Encapsulation is a procedure that takes place at the implementation level, while abstraction is a design-level process.

Advantages of Abstraction

  1. It reduces the complexity of viewing things.

  2. Avoids code duplication and increases reusability.

  3. Helps to increase the security of an application or program as only essential details are provided to the user.

  4. It improves the maintainability of the application.

  5. It improves the modularity of the application.

  6. The enhancement will become very easy because without affecting end-users we can able to perform any type of changes in our internal system.

  7. Improves code reusability and maintainability.

  8. Hides implementation details and exposes only relevant information.

  9. Provides a clear and simple interface to the user.

  10. Increases security by preventing access to internal class details.

  11. Supports modularity, as complex systems can be divided into smaller and more manageable parts.

  12. Abstraction provides a way to hide the complexity of implementation details from the user, making it easier to understand and use.

  13. Abstraction allows for flexibility in the implementation of a program, as changes to the underlying implementation details can be made without affecting the user-facing interface.

  14. Abstraction enables modularity and separation of concerns, making code more maintainable and easier to debug.

Disadvantages of Abstraction:

  1. Abstraction can make it more difficult to understand how the system works.

  2. It can lead to increased complexity, especially if not used properly.

  3. This may limit the flexibility of the implementation.

  4. Abstraction can add unnecessary complexity to code if not used appropriately, leading to increased development time and effort.

  5. Abstraction can make it harder to debug and understand code, particularly for those unfamiliar with the abstraction layers and implementation details.

  6. Overuse of abstraction can result in decreased performance due to the additional layers of code and indirection.

Last updated