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).
Before learning the Java abstract class, let's understand the abstraction in Java first.
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%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
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.
Example of abstract class
1. abstract class A{}
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
1. abstract void printStatus();//no method body and abstract
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.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){[Link]("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
[Link]();
}
}
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: [Link]
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){[Link]("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){[Link]("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape
() method
[Link]();
}
}
drawing circle
Another example of Abstract class in java
File: [Link]
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
[Link]("Rate of Interest is: "+[Link]()+" %");
b=new PNB();
[Link]("Rate of Interest is: "+[Link]()+" %");
}}
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.
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){[Link]("bike is created");}
abstract void run();
void changeGear(){[Link]("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){[Link]("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
[Link]();
}
}
bike is created
running safely..
gear changed
Rule: If there is an abstract method in a class, that class must be abs
Final Method in Java
We can declare Java methods as Final Method by adding the Final keyword before the
method name.
The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the
Final Method is to declare methods of how’s definition can not be changed by a child or
subclass that extends it.
class Bike
{
final void run()
{
[Link]("running");
}
}
public class Honda extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
[Link]();
}
}
Output:Compile Time Error
The above example of the Final Method generates a compile-time error.
As the Bike class Final method was overridden by the Honda class Final method; that is not
possible in the Java programming language.
Purpose of Java Final Methods
The purpose of creating the final methods is to restrict the unwanted and improper use of
method definition while overriding the method.
Though it is not logically incorrect, it can change the meaning of the method and the reader
might interpret it wrongly. Therefore, in such cases to prevent the unwanted method
definitions, we declare methods as final.
Java final class
We can also declare a class with a final keyword in Java. When we declare a class as final,
then we restrict other classes to inherit or extend it.
In short, Java final class can’t be extended by other classes in the inheritance. If another class
attempts to extend the final class, then there will be a compilation error.
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
public class Honda1 extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
[Link]();
}
}
Output:Compile Time Error
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods
declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
Implementation of Interface
The implementation of interfaces can have the following general
forms as shown in the below figure.
}
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Dog "implements" the Animal interface
class Dog implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The dog barks");
}
public void sleep() {
// The body of sleep() is provided here
[Link]("ZzZ");
}
}
class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create a Dog object
[Link]();
[Link]();
}
}
Java does not support “multiple inheritance” which means that a class can only inherit from
one superclass.. However, this can be achieved with interfaces, because a class
can implement multiple interfaces thereby allowing to have multiple inheritance in Java.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an
interface.
Java Interface Example
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its
implementation is provided by Rectangle and Circle classes. In a real
scenario, an interface is defined by someone else, but its implementation
is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses
the interface.
File: [Link]
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){[Link]("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method
e.g. getDrawable()
[Link]();
}}
Output:
drawing circle
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
[Link]();
[Link]();
}
}
Output:Hello
Welcome
Multiple inheritance is not supported through class in java,
but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is
not supported in the case of class because of ambiguity. However, it is
supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class. For
example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){[Link]("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
[Link]();
}
}
Output:
Hello
As you can see in the above example, Printable and Showable interface
have same methods but its implementation is provided by class
TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another
interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
[Link]();
[Link]();
}
}
Output:
Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make
it default method. Let's see an example:
interface Drawable{
void draw();
default void msg(){[Link]("default method");}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]();
}}
Java 8 Static Method in Interface
Since Java 8, we can have static method in interface. Let's see an
example:
File: [Link]
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]([Link](3));
}}
Test it Now
Output:
drawing rectangle
27
Differences between a Class and an Interface:
Class Interface
The keyword used to create a class is The keyword used to create an interface is
“class” “interface”
A class can be instantiated i.e, objects An Interface cannot be instantiated i.e,
of a class can be created. objects cannot be created.
Classes does not support multiple
inheritance. Interface supports multiple inheritance.
It can be inherit another class. It cannot inherit a class.
It can be inherited by a class by using the
keyword ‘implements’ and it can be
It can be inherited by another class inherited by an interface using the keyword
using the keyword ‘extends’. ‘extends’.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract methods. It contains abstract methods only.
Variables and methods in a class can be
declared using any access
specifier(public, private, default, All variables and methods in a interface are
protected) declared as public.
Variables in a class can be static, final
or neither. All variables are static and final.
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many
classes that are related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit
attributes and methods from another class. Polymorphism uses those
methods to perform different tasks. This allows us to perform a single action
in different ways.
For example, think of a superclass called Animal that has a method
called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds -
And they also have their own implementation of an animal sound (the pig
oinks, and the cat meows, etc.):
Example
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
[Link]("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
[Link]("The dog says: bow wow");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
[Link]();
[Link]();
[Link]();
}
}
Why And When To Use "Inheritance" and "Polymorphism"?
- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.