Saturday, May 6, 2023

What is Abstraction in Java? Abstract Class and Interface Example

What is abstraction?
Abstraction in Java or Object-oriented programming is a way to segregate implementation from an interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class, and Object.  Abstraction in Java is achieved by using the interface and abstract class in Java. An interface or abstract class is something that is not concrete, something which is incomplete. In order to use interface or abstract class, we need to extend and implement an abstract method with concrete behavior.

One example of Abstraction is creating an interface to denote common behavior without specifying any details about how that behavior works like you create an interface called Server which has the start() and stop() method.

This is called abstraction of Server because every server should have a way to start and stop and details may differ. 

As I said earlier Abstraction in Java is implemented using abstract class and interface as discussed in the next section. In fact, what is an abstraction in Java, the difference between Abstraction and Encapsulation is also a very popular core Java interview because strong OOPS skill is one of the primary requirements for Java developers? 

Abstraction is also one of the hard to master the concept. The programmer often mixes different levels of abstraction which results in in-flexible code, so be careful with that.





What is an abstract class in Java? Example

An abstract class is something which is incomplete and you can not create an instance of the abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from the abstract class or interface it has implemented or extended. 

By the way, Java has a concept of abstract classes, abstract method but a variable can not be abstract in Java.

A popular example of abstract class in Java is ActionListener which has an abstract method called actionPerformed(ActionEvent ae). This method is called when an ActionEvent is fired like when you click on JButton. It's common in java to attach ActionListener with JButton by implementing abstract method actionPerformed(ActionEvent ae) using Anonymous class, as shown in below Example :

JButton  ok = new JButton("OK");
ok.addActionListener(new ActionListener(){
           public void  actionPerformed(ActionEvent ae){
               //code to handle event
           }
});


An abstract method in Java doesn't have the body , it's just a declaration. In order to use an abstract method, you need to override that method in sub class.

so when do you use abstraction? ( most important in my view )
when you know something needs to be there but not sure how exactly it should look like. e.g. when I am creating a class called Vehicle, I know there should be methods like start() and stop() but don't know how that start and stop method should work, because every vehicle can have a different start and stop mechanism e..g some can be started by kicking or some can be by pressing buttons . The Same concept applies to interface in Java as well, which we will discuss in some other post.

So the implementation of those start() and stop() methods should be left to their concrete implementation e.g. Scooter, MotorBike, Car, etc. See Head First Object-Oriented Analysis and Design book for more details on when to use Abstraction in object-oriented programming.

What is Abstraction in Java




Abstraction Using Interface in Java

What is Abstraction in Java with ExampleIn Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains publicstatic, final constant or abstract methods. It's very common interview question is that where should we use abstract class and where should we use Java Interfaces in my view this is important to understand to design better Java application, you can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don't know how exactly these start and stop method will work. 

If you know some of the behavior while designing class and that would remain common across all subclasses add that into an abstract class. An interface like Runnable interface is a good example of abstraction in Java which is used to abstract task executed by multiple threads. Callable is another good abstract of a task which can return value. 

A picture is worth more than 100 words and this picture proves that. It nicely explanis the concept of data abstraction in object-oriented programming world:
 
Example of Abstraction in Object Oriented Programming


Abstraction: Things to Remember

1) Use abstraction if you know something needs to be in class but the implementation of that varies. Abstraction is actually resulting of thought process and it really need good experience of both domain and Object oriented analysis and design to come up with good abstraction for your project.

2) In Java, you can not create an instance of the abstract class using the new operator, its a compiler error. Though abstract class can have a constructor.

3) abstract is a keyword in Java, which can be used with both class and method.  Abstract class can contain both abstract and concrete method. An abstract method doesn't have the body, just declaration.

4) A class automatically becomes abstract class when any of its methods declared as abstract.

5) abstract method doesn't have a method body.

6) In Java, a variable can not be made abstract , its only class or methods which would be abstract.

7) If a class extends an abstract class or interface it has to provide implementation to all its abstract methods to be a concrete class. alternatively, this class can also be abstract.


Other Object oriented concept tutorials from the Javarevisited blog

52 comments :

Noman Sadiq said...

also add about abstract class can be contain concrete method(method with full definition)

Anonymous said...

Thanks Noman, yes you are correct abstract class can contain concrete method.

Anonymous said...

what is difference between Abstraction and encapsulation , are they similar can we have abstraction along side encapsulation ?

Anonymous said...

what is abstraction in Java, is that same as interface in java, how different abstract class and interface are ?

casanova said...

abstraction is achieved wid da help f encapsulation,,,abstraction means hiding complexity,nd showing functionality,,whereas encap. means wraping or binding methods,objects wid classes,,so here da complexity(i.e.objects,methods) r bind 2gther to hide,,is done wid encapsu. nd showing juss dere functionality 2 da end user iz abstracton,,

casanova said...

dere iz a lil differnce btw. interfaces nd abstraction,a devloper shud uze a abstract class wen he wants 2 acheive 1-99%abstarction,,means wen u knw dat da need f user vl not vary in properties in future,,,whereas interface is used wen u`ve to achieve 100% abstraction ,,,,

Anonymous said...

Can u explain abstraction and encapsulation with simple example?

Javin @ polymorphism in java said...

definitely Anonymous, I will try to write example of abstraction as well as encapsulation in java soon.

siddu said...

i need exact difference between abstract and interface and exact where we use it ?

Anonymous said...

@siddu, major difference between abstract class and interface in Java is that, Interface is complete abstract while Abstract Class can contain non-abstract method.Also everything in interface by default public.In terms of using, interface is generally used to represent behavior e.g. Serializable, Runnable, Clonnable and in Java one Class can extend only one class but multiple interface so it make sense to use interface for behavior than using abstract class in Java.

Anonymous said...

Please explain what is abstract data type?

Rajiv said...

@Anonymous, There is nothing like abstract data type in my knowledge, though you have abstract class in Java which you may refer abstract data type. What is important is that you can not create instance of abstract class in Java, they are incomplete and require to be implemented by sub classes. Abstract classes can or can not contain abstract methods but if you have any abstract method that class automatically becomes abstract in Java.

Anonymous said...

first of all know the difference between abstract class and abstraction and then post anything. but dont tell abstraction used in abstract classes

Guru said...

Can u explain the difference b/w abstraction and polymorphism?

Ghezal Ahmad Zai said...

why every body explain so complicate, everyone has problem, Encapsulation means declaring attribute and methods inside a class, like
class A{
String name;
int number;
public void set(){
.
.
}
}
this is encapsulation.
thanks

shaik said...

That's right

Anonymous said...

Abstraction arises from a reorganization of similarities between certain objects, situations, or processes in the real world, and decision to concentrate upon these similarities and to ignore for the time being the differences.

Anonymous said...

Abstraction is hiding the complaxity and showing only the needed information to the outer world(ex. Abstract classes and Interfaces)

neha said...

abstraction means hiding all the unnecessary details from user. for ex. user dont need to know the inner working of engine and other parts while driving a car.

Unknown said...

Abstraction is a subjective term and encapsulation is objective, like both are the two different view of seeing the one thing. Abstraction says what a object can do, but encapsulation say how that object can do that.

Anonymous said...

Can we create abstract method in a non abstract class in Java? Why it's illegal to use abstract keyword with fields in Java, please explain.

parvesh khan said...

thanx for understanding the concept of abstraction and abatract keyword

Anonymous said...

can static method be abstract? why?

Anonymous said...

Abstraction is hiding complexity and showing functionality.

Anonymous said...

i want to know why we have constructor in abstract class? what are their uses?

Javin @ ClassLoader in Java said...

Hi @Anonymous, Constructor in abstract can used to initialize private fields declared on abstract class itself.

James said...

Abstraction is much more than abstract class and interface. Abstraction is key to design pluggable systems where you can easily replace parts with better ones. Abstraction is closely related to Specification and until your class meets a specification can plug it into System. For example MOUSE in your computer is not tied to any particular company and can be replaced by any company. Abstraction in Java or any Object oriented language is key to design loosely coupled applications.

Anonymous said...

How about level of Abstraction? level of abstraction is very important while declaring, classes, interface and methods. Interface should have higher level of abstraction than methods.

Anonymous said...

Abstraction: showing functionality hiding the implementation which is abtsract, abstraction is showing functionality irrelevent to its implementation in which whose implementation can change overtime with different type of instances but purpose is retained. doing this complexity of its implementation is hidden.

Anonymous said...

in Summary
from point number 4
"a class automatically becomes abstract class when any of its method declared as abstract"

This point is actually incorrect as you need to make class explicitly and compiler will give error if you don't do so

Rahul Askar said...

Really nice post(and comments as well) about Abstraction in Java. Would like to know when to use abstract class and when to use interface?

Javin @ abstract class interface interview questions said...

@Rahul, Thanks, That's great suggestion. I am writing about when to use abstract class and interface in Java, keep in touch or subscribe RSS feed to know about it.

Krishna.... said...

If you are defining a abstract method then you have to declare a class type abstract explicitly. otherwise it will give compiler error.

Unknown said...

hey your blogs is what is abstraction but u r not mentioned meaning of abstractions

Unknown said...

What is use of constructor in Abstract class ?

Liam Rainey said...

To be honest I never understood abstract. (I'm in high school) I mean, why not just make a concrete one and simply not implement it? That way if for some reason you had to implement it you could, and if you don't, no harm done. Can I get an explanation?

Stephen Brown said...

Using Abstract allows you to force someone to implement something.

So something like this would work:

Public void eat () {
putInMouth ();
eatIt ();
swallow ();
}

Public abstract void putInMouth ();
Public abstract void eatIt ();
Public abstract void swallow ();

You would not be able to extend without implementing those 3, they don't have a general or default function. Each animal will do each thing in its own way, make its own. Noise or animation etc...

Anonymous said...

@Liam, abstraction is really nice way to make your programming simpler. It allows you to deal with things which doesn't exists in reality but they are simpler to deal with. A good example of abstration is Queue data structure, which allows two process to share data e.g. in producer consumer problem. This queue can be impelmented using sockets, pipes, or shared memory, but your program don't need to worry about. you also don't need to change your program if underlying implementation of Queue changes. In short, Abstraction make your program more flexible and simpler.

Anonymous said...

When you have written, that "you can not create instance of abstract class"
why there is "new ActionListener()" which is interface based on http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html

TJain said...

Can we override concrete methods of abstract class in it's concrete subclass ot abstract subclass?

Anonymous said...

@Toddler, Yes you can override concrete method of abstract class in its concrete or abstract subclass, provided super class method is not private, static or final as they can't be overridden.

Anonymous said...

@Anonymous, new ActionListener(){ ...} is an example of anonymous class, which is actually a concrete subclass of interface ActionListener, as it implmeents the only abstract method actionPerformed() defined in ActionListener interface. This was a quick way to implement interface or abstract class with single abstract method prior to Java 8, from JDK 8 onwards you can use Lambda expression to implement such interfaces as Lambda in Java are SAM type (Single Abstract Method). There are plenty of those in JDK e.g. Runnable, Callable etc.

Anonymous said...

Hello All,

Abstraction concept in OOP means hiding complicity. someone give example of Queue data structure or other complex logic which you want's to hide from developer and make his/ her life easy.

From my perspective abstract class / interface in Java and Abstraction concept in OOPs both are not same.

Abstraction concept says that hide complexity but Java's Abstract class says that I will not hide anything you write your own complex code. I will just give you and method name which I need. Same way Interface in Java says that here is the method I want you to develop. In both Abstract class and Interface we are not hiding complexity from the developer but we are asking developer to write own code.

From My point of we both are opposite concept. In general abstraction means provide sdk or library or class which contain complex logic and developer can directly use.

Chandan Kumar said...

Please explain how we can achieve abstraction using example.
And please demonstrate how we are abstracting(showing limited but hiding something ) .
And what problem we will get if we wont use abstraction.
Please give some example

Anonymous said...

@Chandan, one example of Abstraction is instead of reading from a file you read from a Reader or InputStream, by doing that you can create classes like java.util.Stream which can create a Stream out of a Reader and that's what lines() method does in Java 8.

Unknown said...

Hello Everyone,

Just to know the simple meaning of abstraction I would like to share one thing that would be I guess simple to understand for all of us.
As we all know the meaning of abstraction i.e Hiding the complexity and showing the functionality.
Like in other way we could say that hiding the unnecessary details from the user and only provide the details that will be rely upon.

I have one example I guess all of us use the software in our daily life like a bank, bank use online softwares or the applications, that the bank work on, so means by abstraction we have been hiding our coding part and only providing the functions like---fetching data, viewing entries of the nominees, so we are only giving the options to use that software by using abstraction, if we provide the coding part then they can make the changes in that part of code.

So likewise only providing the functionality to the clients and hiding the working of that code from the actual client is the main purpose of abstraction.

I hope every one understand that.

Anonymous said...

Please fix the Labels (i.e. from "Labels: core java; object oriented programming" to "Labels: core java, object oriented programming") of this page.

javin paul said...

@Anonymous, good catch, thank you, fixed now.

Yakoob said...

Can anyone explain the real time scenario how you've used Interface and Abstract class in your project.
Please don't give bookish examples or real world examples like Vehicle-Car relationship.

Yakoob said...

Can anyone please provide a real time example how you used Abstract class and Interfaces in your project, which actually gives the real knowledge of Abstraction.
All the bookish definitions like Vehicle - Car all these will give the theoritical knowledge but not the practical knowledge.

Piyush @ abstract class and interface said...

Hey Javin, While abstract classes and interface are used so frequently and heavily in all programming languages, I was wondering who was that brilliant mind that invented the concept of abstract classes. Even after searching for who invented abstract class and history of abstract class, I cannot find any page which lists how abstract classes came into existence. It would be great to know how they originated.

javin paul said...

Hello Piyush, I don't know for sure but Alan Kay is often credited with the invention of object oriented programming and Abstraction is a key OOP concept so he may be the first person to come with the idea of Abstract class and interface.

Post a Comment