Java – Abstract Class

PREV     NEXT

Abstraction:

  • Abstraction is the process of hiding the inner details and showing the functionality.
  • Abstraction can be achieved through abstract class or interface in Java.

Abstract class:

  • A class which is declared as abstract is called abstract class. An abstract class may or maynot contain abstract methods.
  • Abstract method is a method which has no implementation in it or a method without a body.

Example for Abstract method:

abstract void method();

Example for Abstract class:

COMPILE & RUN

Output:

The addition of given numbers is:11

The subtraction of given numbers is:2

  • Abstract class cannot be instantiated. It should only be implemented and used by the subclass.
  •  A subclass which inherits the abstract class either have to implement all the abstract methods present in the abstract class or declare itself as abstract.
  • Every class contain its own variables and methods. Each and every object uses those variables and methods. Suppose if the object needs its own way to perform operations, then we need abstract class.
  • Abstract class is a class which are declared abstract and cannot be instantiated. We cannot create object to an abstract class. We need subclasses which extents the abstract class to use it.

Consider you run a website where you teach how to play cricket, football, hocket etc. You are asking the learners to create a profile. Then you teach them the rules and regulations of the game and how to play the game.


COMPILE & RUN

But all game doesn’t have same rules and same playing methods. So the body of the methods howToPlay() is left empty and is called abstract method.

Abstract method is a method which has no body. Then we create subclass called CricketPlayer to use the abstract method.
PREV     NEXT
Share this website !!!
Facebook Twitter Linkedin