Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
182 views

Abstract Keyword in Java - GeeksforGeeks

Uploaded by

ashoumik112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
182 views

Abstract Keyword in Java - GeeksforGeeks

Uploaded by

ashoumik112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

TutorialsDSAData ScienceWeb TechCourses

Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java Exception H

abstract keyword in java


Last Updated : 02 Apr, 2024
In Java, abstract is a non-access modifier in java applicable for classes, and
methods but not variables. It is used to achieve abstraction which is one of the
pillars of Object Oriented Programming(OOP). Following are different contexts
where abstract can be used in Java.

Characteristics of Java Abstract Keyword


In Java, the abstract keyword is used to define abstract classes and methods.
Here are some of its key characteristics:

Abstract classes cannot be instantiated: An abstract class is a class that


cannot be instantiated directly. Instead, it is meant to be extended by other
classes, which can provide concrete implementations of its abstract
methods.
Abstract methods do not have a body: An abstract method is a method
that does not have an implementation. It is declared using the abstract
keyword and ends with a semicolon instead of a method body. Subclasses
of an abstract class must provide a concrete implementation of all abstract
methods defined in the parent class.
Abstract classes can have both abstract and concrete methods: Abstract
classes can contain both abstract and concrete methods. Concrete methods
are implemented in the abstract class itself and can be used by both the
abstract class and its subclasses.
Abstract classes can have constructors: Abstract classes can have
constructors, which are used to initialize instance variables and perform
other initialization tasks. However, because abstract classes cannot be
instantiated directly, their constructors are typically called constructors in
concrete subclasses.
Abstract classes can contain instance variables: Abstract classes can
contain instance variables, which can be used by both the abstract class and

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 1/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

its subclasses. Subclasses can access these variables directly, just like any
other instance variables.
Abstract classes can implement interfaces: Abstract classes can
implement interfaces, which define a set of methods that must be
implemented by any class that implements the interface. In this case, the
abstract class must provide concrete implementations of all methods
defined in the interface.

Overall, the abstract keyword is a powerful tool for defining abstract classes
and methods in Java. By declaring a class or method as abstract, developers
can provide a structure for subclassing and ensure that certain methods are
implemented in a consistent way across all subclasses.

Abstract Methods in Java


Sometimes, we require just method declaration in super-classes. This can be
achieved by specifying the abstract type modifier. These methods are
sometimes referred to as subclass responsibility because they have no
implementation specified in the super-class. Thus, a subclass must override
them to provide a method definition. To declare an abstract method, use this
general form:

AD

Master Java Programming - Complete Beginner to Advanced LEARN

abstract type method-name(parameter-list);

As you can see, no method body is present. Any concrete class(i.e. Normal
class) that extends an abstract class must override all the abstract methods of
the class.
https://www.geeksforgeeks.org/abstract-keyword-in-java/ 2/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Important rules for abstract methods

There are certain important rules to be followed with abstract methods as


mentioned below:

Any class that contains one or more abstract methods must also be declared
abstract
The following are various illegal combinations of other modifiers for
methods with respect to abstract modifiers:
1. final
2. abstract native
3. abstract synchronized
4. abstract static
5. abstract private
6. abstract strict

Abstract Classes in Java


The class which is having partial implementation(i.e. not all methods present in
the class have method definitions). To declare a class abstract, use this general
form :

abstract class class-name{


//body of class
}

Due to their partial implementation, we cannot instantiate abstract classes.


Any subclass of an abstract class must either implement all of the abstract
methods in the super-class or be declared abstract itself. Some of the
predefined classes in Java are abstract. They depend on their sub-classes to
provide a complete implementation.

For example, java.lang.Number is an abstract class. For more on abstract


classes, see abstract classes in Java.

Examples of abstract Keyword

Example 1:

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 3/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Java

// Java Program to implement


// Abstract Keywords

// Parent Class
abstract class gfg {
abstract void printInfo();
}

// Child Class
class employee extends gfg {
void printInfo()
{
String name = "aakanksha";
int age = 21;
float salary = 55552.2F;

System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}

// Driver Class
class base {
// main function
public static void main(String args[])
{
// object created
gfg s = new employee();
s.printInfo();
}
}

Output

aakanksha
21
55552.2

Example 2:

Java

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 4/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

// Java program to demonstrate


// use of abstract keyword.

// abstract with class


abstract class A {
// abstract with method
// it has no body
abstract void m1();

// concrete methods are still


// allowed in abstract classes
void m2()
{
System.out.println("This is a concrete method.");
}
}

// concrete class B
class B extends A {
// class B must override m1() method
// otherwise, compile-time exception will be thrown
void m1()
{
System.out.println("B's implementation of m1.");
}
}

// Driver class
public class AbstractDemo {
// main function
public static void main(String args[])
{
B b = new B();
b.m1();
b.m2();
}
}

Output

B's implementation of m1.


This is a concrete method.

Example 3:

Java

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 5/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

// Define an abstract class


abstract class Shape {
// Define an abstract method
public abstract double getArea();
}

// Define a concrete subclass of Shape


class Circle extends Shape {
private double radius;

public Circle(double radius) { this.radius = radius; }

public double getArea()


{
return Math.PI * radius * radius;
}
}

// Define another concrete subclass of Shape


class Rectangle extends Shape {
private double width;
private double height;

public Rectangle(double width, double height)


{
this.width = width;
this.height = height;
}

public double getArea() { return width * height; }


}

// Use the Shape class and its subclasses


public class Main {
public static void main(String[] args)
{
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(10, 20);

System.out.println("Circle area: "


+ circle.getArea());
System.out.println("Rectangle area: "
+ rectangle.getArea());
}
}

Output

Circle area: 78.53981633974483


Rectangle area: 200.0

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 6/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Note : Although abstract classes cannot be used to instantiate objects,


they can be used to create object references, because Java’s approach to
run-time polymorphism is implemented through the use of super-class
references. Thus, it must be possible to create a reference to an abstract
class so that it can be used to point to a subclass object.

Advantages of Abstract Keywords

Here are some advantages of using the abstract keyword in Java:

Provides a way to define a common interface: Abstract classes can define


a common interface that can be used by all subclasses. By defining common
methods and properties, abstract classes provide a way to enforce
consistency and maintainability across an application.
Enables polymorphism: By defining a superclass as abstract, you can create
a collection of subclasses that can be treated as instances of the superclass.
This allows for greater flexibility and extensibility in your code, as you can
add new subclasses without changing the code that uses them.
Encourages code reuse: Abstract classes can define common methods and
properties that can be reused by all subclasses. This saves time and reduces
code duplication, which can make your code more efficient and easier to
maintain.
Provides a way to enforce implementation: Abstract methods must be
implemented by any concrete subclass of the abstract class. This ensures
that certain functionality is implemented consistently across all subclasses,
which can prevent errors and improve code quality.
Enables late binding: By defining a common interface in an abstract class,
you can use late binding to determine which subclass to use at runtime. This
allows for greater flexibility and adaptability in your code, as you can
change the behavior of your program without changing the code itself.

abstract and final class in Java


In Java, you will never see a class or method declared with both final and
abstract keywords. For classes, final is used to prevent inheritance whereas

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 7/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

abstract classes depend upon their child classes for complete implementation.
In cases of methods, final is used to prevent overriding whereas abstract
methods need to be overridden in sub-classes.

To know more about the difference between them refer to Difference between
Final and Abstract in Java article.

Feeling lost in the vast world of Backend Development? It's time for a change!
Join our Java Backend Development - Live Course and embark on an exciting
journey to master backend development efficiently and on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks

106 Suggest improvement

Previous Next

Comparison of Inheritance in C++ and Abstract Class in Java


Java

Share your thoughts in the comments Add Your Comment

Similar Reads

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 8/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Difference Between Abstract Class and Difference between Abstract Class and
Abstract Method in Java Concrete Class in Java

Why can't static methods be abstract in Are All Methods in a Java Interface are
Java? Abstract?

Difference between Final and Abstract in Why Java Interfaces Cannot Have
Java Constructor But Abstract Classes Can
Have?

Why a Constructor can not be final, static Can We Instantiate an Abstract Class in
or abstract in Java? Java?

Constructor in Java Abstract Class Implement Interface using Abstract Class


in Java

G Gaurav Miglani

Article Tags : Java-keyword , Java-Object Oriented , Java


Practice Tags : Java

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Hack-A-Thons

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 9/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Legal GfG Weekly Contest


Careers DSA in JAVA/C++
In Media Master System Design
Contact Us Master CP
Advertise with us GeeksforGeeks Videos
GFG Corporate Solution Geeks Community
Placement Training Program

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial Web Templates
ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design
Django Tutorial

Python Tutorial Computer Science


Python Programming Examples Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
https://www.geeksforgeeks.org/abstract-keyword-in-java/ 10/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Web Scraping Software Engineering


OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
AWS Top 50 Tree
Docker Top 50 Graph
Kubernetes Top 50 Array
Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

System Design JavaScript


High Level Design JavaScript Examples
Low Level Design TypeScript
UML Diagrams ReactJS
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

Preparation Corner School Subjects


Company-Wise Recruitment Process Mathematics
Resume Templates Physics
Aptitude Preparation Chemistry
Puzzles Biology
Company-Wise Preparation Social Science
English Grammar
World GK

Management & Finance Free Online Tools


Management Typing Test
HR Management Image Editor

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 11/12
4/25/24, 6:25 PM abstract keyword in java - GeeksforGeeks

Finance Code Formatters


Income Tax Code Converters
Organisational Behaviour Currency Converter
Marketing Random Number Generator
Random Password Generator

More Tutorials GeeksforGeeks Videos


Software Development DSA
Software Testing Python
Product Management Java
SAP C++
SEO - Search Engine Optimization Data Science
Linux CS Subjects
Excel

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/abstract-keyword-in-java/ 12/12

You might also like