0% found this document useful (0 votes)
3 views

Java Abstract Class

The document explains Java abstract classes and methods, highlighting that abstract classes cannot be instantiated and must be declared with the abstract keyword. It details how abstract methods lack implementations and require subclasses to provide those implementations, emphasizing the importance of abstraction in managing complexity in object-oriented programming. Key points include the rules for declaring abstract classes and methods, their usage, and examples demonstrating their functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Abstract Class

The document explains Java abstract classes and methods, highlighting that abstract classes cannot be instantiated and must be declared with the abstract keyword. It details how abstract methods lack implementations and require subclasses to provide those implementations, emphasizing the importance of abstraction in managing complexity in object-oriented programming. Key points include the rules for declaring abstract classes and methods, their usage, and examples demonstrating their functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Java Abstract Class

The abstract class in Java cannot be instantiated (we cannot create


objects of abstract classes).

We use the abstract keyword to declare an abstract class.

For example,

// create an abstract class


abstract class Language
{
// fields and methods
}
...

// try to create an object Language


// throws an error

Language obj = new Language();

An abstract class can have both the regular methods and abstract
methods.

For example,

abstract class Language


{

// abstract method
abstract void method1();

// regular method
void method2() {
System.out.println("This is regular method");
}
}

Java Abstract Method


A method that doesn't have its body is known as an abstract method.
We use the same abstract keyword to create abstract methods. For
example,

abstract void display();

Here, display() is an abstract method.

The body of display() is replaced by ;.

If a class contains an abstract method, then the class should be declared


abstract.
Otherwise, it will generate an error. For example,

// error
// class should be abstract
class Language {

// abstract method
abstract void method1();
}
Example: Java Abstract Class and Method

Though abstract classes cannot be instantiated, we can create


subclasses from it.
We can then access members of the abstract class using the object of
the subclass. For example,

abstract class Language


{
// method of abstract class
public void display()
{
System.out.println("This is Java Programming");
}
}

class Main extends Language


{
public static void main(String[] args)
{
// create an object of Main
Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();
}
}

Output

This is Java programming

In the above example, we have created an abstract class named


Language. The class contains a regular method display().
We have created the Main class that inherits the abstract class. Notice
the statement,

obj.display();
Here, obj is the object of the child class Main. We are calling the
method of the abstract class using the object obj.

Implementing Abstract Methods


If the abstract class includes any abstract method, then all the child
classes inherited from the abstract superclass must provide the
implementation of the abstract method. For example,

abstract class Animal {


abstract void makeSound();

public void eat() {


System.out.println("I can eat.");
}
}

class Dog extends Animal {

// provide implementation of abstract method


public void makeSound() {
System.out.println("Bark bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of Dog class


Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
Run Code
Output

Bark bark
I can eat.

In the above example, we have created an abstract class Animal. The


class contains an abstract method makeSound() and a non-abstract
method eat().

We have inherited a subclass Dog from the superclass Animal. Here, the
subclass Dog provides the implementation for the abstract method
makeSound().

We then used the object d1 of the Dog class to call methods


makeSound() and eat().

Note: If the Dog class doesn't provide the implementation of the


abstract method makeSound(), Dog should also be declared as abstract.
This is because the subclass Dog inherits makeSound() from Animal.

Accesses Constructor of Abstract Classes


An abstract class can have constructors like the regular class.
And, we can access the constructor of an abstract class from the
subclass using the super keyword.
For example,
abstract class Animal {
Animal() {
….
}
}

class Dog extends Animal {


Dog() {
super();
...
}
}

Here, we have used the super() inside the constructor of Dog to access
the constructor of the Animal.

Note that the super should always be the first statement of the subclass
constructor. Visit Java super keyword to learn more.

Java Abstraction

The major use of abstract classes and methods is to achieve abstraction


in Java.

Abstraction is an important concept of object-oriented programming


that allows us to hide unnecessary details and only show the needed
information.

This allows us to manage complexity by omitting or hiding details with a


simpler, higher-level idea.

A practical example of abstraction can be motorbike brakes.


We know what brake does.
When we apply the brake, the motorbike will stop.
However, the working of the brake is kept hidden from us.

The major advantage of hiding the working of the brake is that now the
manufacturer can implement brake differently for different motorbikes,
however, what brake does will be the same.

Let's take an example that helps us to better understand Java


abstraction.

Example 3:
Java Abstraction

abstract class MotorBike {


abstract void brake();
}

class SportsBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("SportsBike Brake");
}
}

class MountainBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("MountainBike Brake");
}
}
class Main {
public static void main(String[] args) {
MountainBike m1 = new MountainBike();
m1.brake();
SportsBike s1 = new SportsBike();
s1.brake();
}
}
Run Code
Output:

MountainBike Brake
SportsBike Brake

In the above example, we have created an abstract super class


MotorBike.

The superclass MotorBike has an abstract method brake().

The brake() method cannot be implemented inside MotorBike.

It is because every bike has different implementation of brakes.

So, all the subclasses of MotorBike would have different


implementation of brake().

So, the implementation of brake() in MotorBike is kept hidden.

Here, MountainBike makes its own implementation of brake() and


SportsBike makes its own implementation of brake().

Note: We can also use interfaces to achieve abstraction in Java.


Key Points to Remember
• We use the abstract keyword to create abstract classes and
methods.
• An abstract method doesn't have any implementation (method
body).
• A class containing abstract methods should also be abstract.
• We cannot create objects of an abstract class.
• To implement features of an abstract class, we inherit subclasses
from it and create objects of the subclass.
• A subclass must override all abstract methods of an abstract class.
However, if the subclass is declared abstract, it's not mandatory to
override abstract methods.

• We can access the static attributes and methods of an abstract


class using the reference of the abstract class.
Abstract Classes and Abstract Methods in Java

Abstract Classes and Abstract Methods in Java


Note: A method that does not have a body is called an abstract method
and the class that is declared by using the abstract keyword is called an
abstract class. If a class contains an abstract method, then it must be
declared as abstract.

What is the abstract class in java?


A class that is declared by using the abstract keyword is called an
abstract class in java. It is a partially implemented class used for
developing some of the operations of an object which are common for
all next level subclasses. So it contains both abstract methods, concrete
methods including variables, blocks, and constructors.
It is always created as a superclass next to the interface in the object
inheritance hierarchy for implementing common operations from the
interface. An abstract class may or may not have abstract methods. But
if a class contains an abstract method then it must be declared as
abstract.

What is Abstract Method in Java?


A method that does not have a body is called an abstract method in
Java. It is declared with the modifier abstract.

The following are the properties of the java abstract method,

• It can only be used in an abstract class, and it does not have a


body.
• An abstract method contains a method signature, but no method
body.
• An abstract method is a method that is declared without
implementation.
• Instead of curly braces, an abstract method will have a semicolon
(;) at the end.
• A method-defined abstract must always be redefined in the
subclass, thus making overriding compulsory OR either making the
subclass itself abstract.

Why method should have an abstract keyword if it does not have a


body?
In a class, we are allowed only to define a class with a body. Since we
are changing its default behavior (which means removing its body) it
must have an abstract keyword in its prototype.

When a class should be declared abstract in Java?


A class should be declared as abstract
• If it has any abstract methods
• If it does not provide implementation to any of the abstract
methods it inherited
• If it does not provide implementation to any of the methods of an
interface.

When to use Abstract Methods in Java?


Abstract methods are usually declared where two or more subclasses
are expected to fulfill a similar role in different ways. Often the
subclasses are required to fulfill an interface, so the abstract superclass
might provide several of the interface methods, but leave the
subclasses to implement their own variations of the abstract methods.
Abstract classes can be thought of as part-complete templates that
make it easier to write a series of subclasses.

Rules of Abstract Class and Abstract Methods in Java:


Rule1:

If the method does not have a body it should be declared as abstract


using the abstract modifier else it leads to CE: “missing method body or
declared abstract”
public class Example
{
void m1(); //CE: missing method body or declared abstract
}

CE: missing method body or declared abstract

Rule2:
If a class has an abstract method it should be declared as abstract by
using the keyword abstract else it leads to CE: class is not abstract and
does not override the abstract method in the class.
public class Example
{
abstract void m1();
}
CE: Example is not abstract and does not override abstract method
m1() in Example. The correct syntax is given below.
abstract class Example
{
abstract void m1();
}

Rule3:
If a class is declared as abstract it cannot be instantiated violation leads
to compile-time Error.
abstract class Example
{
abstract void m1();
public static void main(String args[])
{
Example e = new Example();
}
}
CE: Example is abstract, cannot be instantiated

Why abstract class cannot be instantiated?


Because it is not a fully implemented class so its abstract methods
cannot be executed. If the compiler allows us to create an object for an
abstract class we can invoke the abstract method using that object
which cannot be executed by JVM at runtime. Hence to restrict calling
abstract methods, the compiler does not allow us to instantiate an
abstract class.

Who will provide implementation (body) for abstract methods?


Sub-class developers provide the body for abstract methods according
to their business requirements. Basically in projects, abstract methods
(method prototypes) are defined by superclass developers and they are
implemented by sub-class developers. Implemented means providing
the method body with logic.

Rule4:
The subclass of an abstract class should override all abstract methods or
it should be declared as abstract else it leads to CE:

abstract class Example


{
abstract void m1();
abstract void m2();
}
class Sample extends Example
{
void m1()
{
System.out.println("m1 method");
}
}
Solutions:
Declare the class as abstract
abstract class Sample extends Example
{
void m1 ()
{
System.out.println ("m1 method");
}
}

Override both abstract methods


abstract class Sample extends Example
{
void m1()
{
System.out.println("m1 method");
}
void m2()
{
System.out.println("m2 method");
}
}

Can we declare an abstract method as static?


No, we are not allowed to declare an abstract method as static.
It leads to CE: illegal combination of modifier abstract and static.
If the compiler allows us to declare it as static, it can be invoked directly
which cannot be executed by JVM at runtime.
Hence to restrict calling abstract methods compiler does not allow us to
declare an abstract method as static.

For example
abstract class Example
{
static abstract void m1(); //CE: illegal combination of modifier abstract
abstract void m2(); // and static
}

Can we declare an abstract method as final?


No, because it should be allowed to override in subclasses.

It leads to CE: illegal combination of modifier abstract and final.

For example:
abstract class Example
{
final abstract void m1(); //CE: illegal combination of modifier abstract
abstract void m2(); // and final
}

Can we declare an abstract method as private?


No, because it should be inherited by subclasses. It leads to CE: illegal
combination of modifier abstract and private.

For example:
abstract class Example
{
private abstract void m1(); //CE: illegal combination of modifier
abstract
abstract void m2(); // and private
}

Can we declare a concrete class as abstract in Java?


Yes, it is allowed. Defining a class as abstract is a way of preventing
someone from instantiating a class that is supposed to be extended
first.

To ensure our class non-static members are only accessible via sub-class
objects we should declare the concrete class as abstract.

Predefined concrete abstract classes are


• java.awt.Component
• javax.servlet.http.HttpServlet

let us see an example for a better understanding

A concrete class declared as abstract in Java


abstract class Example
{
static void m1()
{
System.out.println("Example m1 method");
}
void m2()
{
System.out.println("Example m2 method");
}
}
Calling concrete abstract members from normal class
class Sample
{
public static void main(String args[])
{
Example.m1();

Example e = new Example();//CE: cannot be instantiated class Example


e.m2();
}
}

Calling concrete abstract class members from sub-classes

class Sample extends Example


{
public static void main(String args[])
{
Example.m1();
Sample e = new Sample();
e.m2();
}
}
Output:
Example m1 method
Example m2 method
Difference Between Abstract class and Concrete class in Java:
Abstract Class in Java Concrete Class in Java
A class declared with an A class that allows creating
abstract keyword which is a an instance of an object
collection of abstract and using the new keyword.
non-abstract methods.
We cannot create an object We can create an object
using an abstract class. using an abstract class.
An abstract class can have All methods in a concrete
unimplemented methods. class are implemented.

When to use Abstract Classes and Abstract Methods in Java?


There are situations in which we will want to define a superclass that
declares the structure of a given abstraction without providing a
complete implementation of every method. That is, sometimes we want
to create a superclass that only defines a generalization form that will
be shared by all of its subclasses, leaving it to each subclass to fill in the
details.

Consider a classic “Bank”, the base type is “Bank” and each bank has a
Rate Of Interest, etc.

From this, specific types of banks are derived (inherited)-SBI, HDFC,


PNB, etc. – each of which may have additional characteristics and
behaviors.

For example, all banks may have different Rates of Interest.

The type hierarchy embodies both the similarities and differences


between the banks.
Sample Program for Abstract classes and Abstract Methods:
public class Main
{
public static void main (String[]args)
{
Bank b;
b = new SBI ();
System.out.println ("SBI Rate of Interest is: " + b.getRateOfInterest () +
" %");
b = new PNB ();
System.out.println ("PNB Rate of Interest is: " + b.getRateOfInterest ()
+" %");
}
}

abstract class Bank


{
abstract int getRateOfInterest ();
}
class SBI extends Bank
{
int getRateOfInterest ()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest ()
{
return 8;
}
}
Output:

What type of members we can define in an abstract class?


We can define all static and non-static members including constructors
and also abstract methods.

Will abstract class members are created when a subclass object is


created?
Yes, its non-static members get memory when its concrete sub-class
object is created.

Abstraction in Java with Examples


In this article, I am going to discuss Abstraction in Java with Examples.
Please read our previous where we discussed Inheritance in Java with
Examples. At the end of this article, you will understand what is
Abstraction in Java and when and how to implement Abstraction in Java
with examples.

Note: What we will do here is, first we will create a real-time example
without using Abstraction, then we will identify the problem, and finally
we will see how to overcome the problem using abstraction in java.

What is Abstraction in Java?


Data Abstraction may also be defined as the process of identifying only
the required characteristics of an object ignoring the irrelevant details.
Abstraction is nothing but the quality of dealing with ideas rather than
events. Abstraction is selecting data from a larger pool to show only the
relevant details of the object to the user.

In more simple words we can say that Abstraction in Java is a process of


defining a class by exposing the necessary and essential (compulsory)
details to the outside world by hiding the unnecessary things (or
complexity or implementation details). That means you only need to
expose what is necessary and compulsory and need to hide the
unnecessary things to the outside world. In Java, by using the private
access modifiers, you can hide the member of a class.

Types of Abstractions in Java:


Typically abstraction can be seen in two ways:
1. Data Abstraction
2. Control Abstraction

Data abstraction in Java:


Data abstraction is the way to create complex data types and expose only
meaningful operations to interact with the data type, whereas hiding all
the implementation details from outside works. The benefit of this
approach involves the capability of improving the implementation over
time e.g. solving performance issues if any.

The idea is that such changes are not supposed to have any impact on
client code since they involve no difference in abstract behavior.

Control abstraction in Java:


Software is essentially a collection of numerous statements written in any
programming language. Most of the time, statements are similar and
repeated over places multiple times.
Control abstraction is the process of identifying all such statements and
exposing them as a unit of work. We normally use this feature when we
create a function to perform any work.

Real-Time Example of an Abstraction using Java:


Suppose you want to create an ATM Machine and you are asked to collect
all the information about the operations of the ATM Machine. There are
chances that you will come up with the following information.
• Cash Withdrawal
• Money transfer
• Mini statement

You might have used ATM machines many times for cash withdrawal
and bank statements.

The ATM Machine has given a card swipe slot, a touch screen, and a
keyboard, you can use these features to withdraw the money but you
never know what exact actions or operations takes place internally in
the machine-like after a card swipe the machine checks whether the
card is valid or not, then the PIN will be verified if it is correct then only
we can withdraw the money but the withdraw money should not be
greater than the available balance.

Example: Implementing ATM Machine using Java


Let us implement the above-discussed example using java. The
following is our ATM Machine class and if you further notice, here we
declared each and every method as public.

class ATMMachine
{
public void Enter_Card()
{
System.out.println ("Card Verification");
}

public void Enter_Pin()


{
System.out.println ("Pin Verification");
}

public void Cash_Withdrawal ()


{
System.out.println ("To withdraw cash from ATM");
}

public void Validate_Withdraw_Amount()


{
System.out.println ("Validate the Amount to be withdraw");
}

public void Update_Amount()


{
System.out.println ("Update the Amount after withdraw");
}

public void Cash_Dispose()


{
System.out.println ("Disponse the cash from ATM");
}

public void Mini_Statement ()


{
System.out.println ("Get the mini statement");
}
}

As you can see, in the above code, now the user of our ATM Machine
class can call the methods and perform the necessary actions as shown
in the below code.
public class Main
{
public static void main (String[]args)
{
ATMMachine am = new ATMMachine ();
//Accessing the Public Properties and methods
am.Enter_Card();
am.Enter_Pin();
am.Cash_Withdrawal();
am.Validate_Withdraw_Amount();
am.Update_Amount();
am.Cash_Dispose();
}
}
Output:
As you can see in the above image, you get the output as expected.
Now, let us move and analyze the code. Do, we really need to call the
following three methods manually.
Validate_Withdraw_Amount();
Update_Amount();
Cash_Dispose();
The way we have implemented the code in our ATMMachine class if the
withdrawal amount is less than the available balance, then also it is
going to perform the withdrawal operation. At the same time, the user
of the ATM Machine class may forget to call some of the methods as
shown in the below code.
public class Main
{
public static void main (String[]args)
{
ATMMachine am = new ATMMachine ();
//Accessing the Public Properties and methods
am.Enter_Card();
am.Enter_Pin();
am.Cash_Withdrawal();
am.Cash_Dispose();
}
}
Output:

Why this is happening?


Because we are not following the Abstraction Principle. As we made all
the methods public, so the user of the ATMMachine class can access all
these methods.

How to solve the above problem?


By using the abstraction principle. The methods which you want to
expose, make them public and the methods which you don’t want to
expose, make them private. So, let us first modify the ATMMachine
class as shown below.
class ATMMachine
{
public void Enter_Card ()
{
System.out.println ("Card Verification");
}

public void Enter_Pin ()


{
System.out.println ("Pin Verification");
}

public void Cash_Withdrawal ()


{
System.out.println ("To withdraw cash from ATM");
Validate_Withdraw_Amount ();
Update_Amount ();
Cash_Dispose ();
}

private void Validate_Withdraw_Amount ()


{
System.out.println ("Validate the Amount to be withdraw");
}

private void Update_Amount ()


{
System.out.println ("Update the Amount after withdraw");
}

private void Cash_Dispose ()


{
System.out.println ("Disponse the cash from ATM");
}

public void Mini_Statement ()


{
System.out.println ("Get the mini statement");
}
}

As you can see in the above code, the necessary methods and
properties are exposed by using the “public” access modifier whereas
the unnecessary methods and properties are hidden from outside the
world by using the “private” access modifier.
We made the following methods private, so they are not exposed to the
user of the ATMMachine class.

As part of the Cash_Withdrawal, we need to put the required logic to


call methods.

Validate_Withdraw_Amount();
Update_Amount();
Cash_Dispose();

Now, modify the Main class as shown below.

public class Main


{
public static void main (String[]args)
{
ATMMachine am = new ATMMachine ();
//Accessing the Public Properties and methods
am.Enter_Card ();
am.Enter_Pin ();
am.Cash_Withdrawal ();
}
}

Output:
Now, from the Main class (or the user of the ATMMachine class), if you
try to call the following methods then you will get a compile-time error.

Validate_Withdraw_Amount();
Update_Amount();
Cash_Dispose();
Now, we are exposing the necessary methods (Enter_Card, Enter_Pin,
and Cash_Withdrawal) to the outside world or to the user of the
ATMMachine class by hiding its implementation details or the
Complexity (Validate_Withdraw_Amount, Update_Amount, and
Cash_Dispose). This is called abstraction in Java.

Advantages of Abstraction in Java:


• It reduces the complexity of viewing things and increases the
readability of the code.

• Helps to increase the security of an application or program


as only important details are provided to the user.

Difference Between Abstraction and Encapsulation in Java:


Abstraction in Java Encapsulation in Java
Refers to showing only Means to hide (data hiding).
the necessary details to Wrapping and just hiding
the intended users. properties and methods.
Used in programming Used to hide the code and
languages to make data in a single unit to
abstract classes. protect the data from the
outside world.
It is implemented using It is implemented using a
abstract classes and private and protected access
interfaces. modifier.

You might also like