Skip to content

Quick Guide To Abstraction

Junx edited this page Sep 9, 2020 · 2 revisions

Quick Guide To abstraction and the abstract class

A quick summary of abstraction in oop and abstract classes from lecture 2 and 3. There is a TLDR at the bottom. Enjoy!

Abstraction

"Where similar functions are carried out by distinct pieces of code, it is generally beneficial to combine them into one by abstracting out the varying parts" by Benjamin C. Pierce

What is abstraction?

  • Abstraction in OOP allows the programmer to hide all but the relevant data about an object in order to reduce the complexity and increase the efficiency of the program.
  • Objects in OOP allow programmers to hide the internal implementation details in their objects and only call upon them the methods when needed.

Example of abstraction in java

An example of abstraction in java is the use of packages such as java.lang.math where you just need to know which methods of the package are available and which input parameters are needed to trigger a specific operation. But you don’t need to understand how this method is implemented and which kinds of actions it has to perform to create the expected result.

Abstract Classes

Abstract class in Java is similar to interface except that it can contain default method implementation. An abstract class can have an abstract method without body and it can have methods with implementation also.

  • Abstract Classes cannot be instantiated as their main purpose
  • If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
  • If an abstract class doesn’t have any method implementation, it's better to use interface because java doesn’t support multiple class inheritance.
  • The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.

What are abstract Classes for?

An abstract class is mostly used to provide a base for subclasses to extend and implement the abstract methods and override or use the implemented methods in the abstract class. The goal of this is to allow for Inheritance and to make a class well defined by the abstract method. (Refer to slide 15 lecture note 3 for an example)

TLDR

Abstraction can be achieved by using the abstract class to hide certain code implementations. Java Abstract class is used to provide common method implementation to all the subclasses or to provide a default implementation.

References

  1. What is abstraction?
  2. Abstract Class
Clone this wiki locally