You are on page 1of 7

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).

A class that is declared using “abstract” keyword is known as abstract class. It


can have abstract methods(methods without body) as well as concrete methods
(regular methods with body). A normal class(non-abstract class) cannot have
abstract methods.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Why we need an abstract class?


Lets say we have a class Animal that has a method sound() and the subclasses(see inheritance) of
it like Dog, Lion, Horse, Cat etc. Since the animal sound differs from one animal to another, there
is no point to implement this method in parent class. This is because every child class must override
this method to give its own implementation details, like Lion class will say “Roar” in this method
and Dog class will say “Woof”.

So when we know that all the animal child classes will and should override this method, then there
is no point to implement this method in parent class. Thus, making this method abstract would be
the good choice as by making this method abstract we force all the sub classes to implement this
method( otherwise you will get compilation error), also we need not to give any implementation
to this method in parent class.

Abstract class Example


//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{
public void sound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}
Output:

Woof

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Rules

Note 1: As we seen in the above example, there are cases when it is difficult or often unnecessary
to implement all the methods in parent class. In these cases, we can declare the parent class as
abstract, which makes it a special class which is not complete on its own.

A class derived from the abstract class must implement all those methods that are declared as
abstract in the parent class.

Note 2: Abstract class cannot be instantiated which means you cannot create the object of it. To
use this class, you need to create another class that extends this this class and provides the
implementation of abstract methods, then you can use the object of that child class to call non-
abstract methods of parent class as well as implemented methods(those that were abstract in parent
but implemented in child class).

Note 3: If a child does not implement all the abstract methods of abstract parent class, then the
child class must need to be declared abstract as well.

Do you know? Since abstract class allows concrete methods as well, it does not provide 100%
abstraction. You can say that it provides partial abstraction. Abstraction is a process where you
show only “relevant” data and “hide” unnecessary details of an object from the user.

Interfaces on the other hand are used for 100% abstraction (See more about abstraction here).
You may also want to read this: Difference between abstract class and Interface in Java

Why can’t we create the object of an abstract class?

Because these classes are incomplete, they have abstract methods that have no body so if java
allows you to create object of this class then if someone calls the abstract method using that object
then What would happen?There would be no actual implementation of the method to invoke.
Also because an object is concrete. An abstract class is like a template, so you have to extend it
and build on it before you can use it.

For now lets just see some basics and example of abstract method.
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden. An abstract class must be extended and in a same
way abstract method must be overridden.
4) A class has to be declared abstract to have abstract methods.

Abstract Method in Java


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

Syntax of abstract method

1. abstract void printStatus();//no method body and abstract

Like C++, in Java, an instance of an abstract class cannot be created, we can have
references of abstract class type though.
abstract class Base {
abstract void fun();
}
class Derived extends Base {
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {

// Uncommenting the following line will cause compiler error as the


// line tries to create an instance of abstract class.
// Base b = new Base();

// We can have references of Base type.


Base b = new Derived();
b.fun();
}
}
2. Run on IDE
3. Output:
4. Derived fun() called

Like C++, an abstract class can contain constructors in Java. And a constructor of abstract
class is called when an instance of a inherited class is created. For example, the following is
a valid Java program.
// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}
Output:

Base Constructor Called

Derived Constructor Called

3) In Java, we can have an abstract class without any abstract method. This allows us to
create classes that cannot be instantiated, but can only be inherited.
// An abstract class without any abstract method
abstract class Base {
void fun() { System.out.println("Base fun() called"); }
}

class Derived extends Base { }

class Main {
public static void main(String args[]) {
Derived d = new Derived();
d.fun();
}
}
Run on IDE
Output:

Base fun() called

4) Abstract classes can also have final methods (methods that cannot be overridden). For
example, the following program compiles and runs fine.
// An abstract class with a final method
abstract class Base {
final void fun() { System.out.println("Derived fun() called"); }
}

class Derived extends Base {}

class Main {
public static void main(String args[]) {
Base b = new Derived();
b.fun();
}
}

Output:

Derived fun() called

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. } }
running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about
the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g.,
getShape() method
15. s.draw();
16. } }
drawing circle

Another example of Abstract class in java


File: TestBank.java

1. abstract class Bank{


2. abstract int getRateOfInterest(); }
3. class SBI extends Bank{
4. int getRateOfInterest(){return 7;}
5. }
6. class PNB extends Bank{
7. int getRateOfInterest(){return 8;}
8. }

9. class TestBank{
10. public static void main(String args[]){
11. Bank b;
12. b=new SBI();
13. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
14. b=new PNB();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16. }}
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data member and


methods
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.

File: TestAbstraction2.java

1. //Example of an abstract class that has abstract and non-abstract methods


2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7. //Creating a Child class which inherits Abstract class
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. //Creating a Test class which calls abstract and non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. } }
bike is created
running safely..
gear changed
Rule: If there is an abstract method in a class, that class must be abstract.

1. class Bike12{
2. abstract void run();
3. }
compile time error

Rule: If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.

abstract method in an abstract class


//abstract class
abstract class Sum{
/* These two are abstract methods, the child class
* must implement these methods
*/
public abstract int sumOfTwo(int n1, int n2);
public abstract int sumOfThree(int n1, int n2, int n3);

//Regular method
public void disp(){
System.out.println("Method of class Sum");
}
}
//Regular class extends abstract class
class Demo extends Sum{

/* If I don't provide the implementation of these two methods, the


* program will throw compilation error.
*/
public int sumOfTwo(int num1, int num2){
return num1+num2;
}
public int sumOfThree(int num1, int num2, int num3){
return num1+num2+num3;
}
public static void main(String args[]){
Sum obj = new Demo();
System.out.println(obj.sumOfTwo(3, 7));
System.out.println(obj.sumOfThree(4, 3, 19));
obj.disp();
}
}
Output:

10
26
Method of class Sum

You might also like