0% found this document useful (0 votes)
17 views19 pages

JAVA Abstract

An abstract class in Java is declared with the 'abstract' keyword and cannot be instantiated, requiring subclassing for implementation. It can contain both abstract methods (without a body) and non-abstract methods (with a body), and serves as a way to achieve abstraction by hiding implementation details. Key points include that abstract classes can have constructors, static methods, and can exist without abstract methods, but any class with at least one abstract method must be declared abstract.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views19 pages

JAVA Abstract

An abstract class in Java is declared with the 'abstract' keyword and cannot be instantiated, requiring subclassing for implementation. It can contain both abstract methods (without a body) and non-abstract methods (with a body), and serves as a way to achieve abstraction by hiding implementation details. Key points include that abstract classes can have constructors, static methods, and can exist without abstract methods, but any class with at least one abstract method must be declared abstract.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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).

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 we type the text and send the message. We don't know
the internal processing about the message delivery.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Java Abstraction
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract
classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and


methods:

 Abstract class: is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does


not have a body. The body is provided by the subclass (inherited
from).

 An abstract class can have both abstract and regular methods:

abstract class Animal {

public abstract void animalSound();


public void sleep() {

System.out.println("Zzz");

From the example above, it is not possible to create an object of the Animal
class:

Animal myObj = new Animal(); // will generate an error

Example
// Abstract class

abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

}
class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

Output

The pig says: wee wee


Zzz

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.

In Java, abstract class is declared with the abstract keyword. It may have
both abstract and non-abstract methods(methods with bodies). An
abstract is a Java modifier applicable for classes and methods in Java
but not for Variables. In this article, we will learn the use of abstract
classes in Java.
What is Abstract Class in Java?
Java abstract class is a class that can not be instantiated by itself, it
needs to be subclassed by another class to use its properties. An abstract
class is declared using the “abstract” keyword in its class definition.
Abstract classes are a key component of OOP in Java, allowing you to
define incomplete classes that other classes can extend. For a deeper
exploration of abstract classes and their applications, the Java
Programming Course provides detailed lessons with practical projects.
Illustration of Abstract class
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
In Java, the following some important observations about abstract classes
are as follows:
1. An instance of an abstract class can not be created.
1. Constructors are allowed.
1. We can have an abstract class without any abstract method.
1. There can be a final method in abstract class but any abstract method
in class(abstract class) can not be declared as final or in simpler terms
final method can not be abstract itself as it will yield an error: “Illegal
combination of modifiers: abstract and final”
1. We can define static methods in an abstract class
1. We can use the abstract keyword for declaring top-level classes
(Outer class) as well as inner classes as abstract
1. If a class contains at least one abstract method then compulsory
should declare a class as abstract
1. If the Child class is unable to provide implementation to all abstract
methods of the Parent class then we should declare that Child class
as abstract so that the next level Child class should provide
implementation to the remaining abstract method
Examples of Java Abstract Class
1. Example of Abstract Class that has Abstract method

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.
2. abstract class Bike{
3. abstract void run();
4. }
5. class Honda4 extends Bike{
6. void run(){System.out.println("running safely");}
7. public static void main(String args[]){
8. Bike obj = new Honda4();
9. obj.run();
10. }
11. }
OUTPUT
running safely

// Abstract class
abstract class Sunstar {
abstract void printInfo();
}

// Abstraction performed using extends


class Employee extends Sunstar {
void printInfo()
{
String name = "avinash";
int age = 21;
float salary = 222.2F;

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

// Base class
class Base {
public static void main(String args[])
{
Sunstar s = new Employee();
s.printInfo();
}
}
Output
avinash
21
222.2
2. Abstract Class having constructor, data member, and methods
Elements abstract class can have
 data member
 abstract method
 method body (non-abstract method)
 constructor
 main() method.
Below is the implementation of the above topic:
// Java Program to implement Abstract Class
// having constructor, data member, and methods
import java.io.*;

abstract class Subject {


Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus();

void Learn(){
System.out.println("Preparing Right Now!");
}
}

class IT extends Subject {


void syllabus(){
System.out.println("C , Java , C++");
}
}

class GFG {
public static void main(String[] args) {
Subject x=new IT();

x.syllabus();
x.Learn();
}
}
Output
Learning Subject
C , Java , C++
Preparing Right Now!
Properties of Abstract class
Let us elaborate on these observations and do justify them with help of
clean java programs as follows.
Observation 1
In Java, just like in C++ an instance of an abstract class cannot be
created, we can have references to abstract class type though. It is as
shown below via the clean Java program.
// Java Program to Illustrate
// that an instance of Abstract
// Class can not be created
// Class 1
// Abstract class
abstract class Base {
abstract void fun();
}

// Class 2
class Derived extends Base {
void fun()
{
System.out.println("Derived fun() called");
}
}

// Class 3
// Main class
class Main {

// Main driver method


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();
}
}

Output
Derived fun() called
Observation 2
Like C++, an abstract class can contain constructors in Java. And a
constructor of an abstract class is called when an instance of an inherited
class is created. It is as shown in the program below as follows:
Example:
Java
// Java Program to Illustrate Abstract Class
// Can contain Constructors

// Class 1
// Abstract class
abstract class Base {

// Constructor of class 1
Base()
{
// Print statement
System.out.println("Base Constructor Called");
}

// Abstract method inside class1


abstract void fun();
}

// Class 2
class Derived extends Base {

// Constructor of class2
Derived()
{
System.out.println("Derived Constructor Called");
}

// Method of class2
void fun()
{
System.out.println("Derived fun() called");
}
}

// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating object of class 2
// inside main() method
Derived d = new Derived();
d.fun();
}
}

Output
Base Constructor Called
Derived Constructor Called
Derived fun() called
Observation 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. It is as shown below as follows with help of a clean
java program.
Example:
Java
// Java Program to illustrate Abstract class
// Without any abstract method

// Class 1
// An abstract class without any abstract method
abstract class Base {

// Demo method. This is not an abstract method.


void fun()
{
// Print message if class 1 function is called
System.out.println(
"Function of Base class is called");
}
}

// Class 2
class Derived extends Base {
// This class only inherits the Base class methods and
// properties
}

// Class 3
class Main {

// Main driver method


public static void main(String args[])
{
// Creating object of class 2
Derived d = new Derived();

// Calling function defined in class 1 inside main()


// with object of class 2 inside main() method
d.fun();
}
}

Output
Function of Base class is called
Observation 4
Abstract classes can also have final methods (methods that cannot be
overridden)
Example:
Java
// Java Program to Illustrate Abstract classes
// Can also have Final Methods

// Class 1
// Abstract class
abstract class Base {

final void fun()


{
System.out.println("Base fun() called");
}
}

// Class 2
class Derived extends Base {

// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
{
// Creating object of abstract class

Base b = new Derived();


// Calling method on object created above
// inside main method

b.fun();
}
}
}

Output
Base fun() called
Observation 5
For any abstract java class we are not allowed to create an object i.e., for
an abstract class instantiation is not possible.
Java
// Java Program to Illustrate Abstract Class

// Main class
// An abstract class
abstract class GFG {
// Main driver method
public static void main(String args[])
{

// Trying to create an object


GFG gfg = new GFG();
}
}
Output:

Observation 6
Similar to the interface we can define static methods in an abstract
class that can be called independently without an object.
Java
// Java Program to Illustrate
// Static Methods in Abstract
// Class Can be called Independently

// Class 1
// Abstract class
abstract class Helper {

// Abstract method
static void demofun()
{

// Print statement
System.out.println("Geeks for Geeks");
}
}

// Class 2
// Main class extending Helper class
public class GFG extends Helper {

// Main driver method


public static void main(String[] args)
{
// Calling method inside main()
// as defined in above class
Helper.demofun();
}
}

Output
Geeks for Geeks
Observation 7
We can use the abstract keyword for declaring top-level classes (Outer
class) as well as inner classes as abstract
Java
import java.io.*;

abstract class B {
// declaring inner class as abstract with abstract
// method
abstract class C {
abstract void myAbstractMethod();
}
}
class D extends B {
class E extends C {
// implementing the abstract method
void myAbstractMethod()
{
System.out.println(
"Inside abstract method implementation");
}
}
}

public class Main {

public static void main(String args[])


{
// Instantiating the outer class
D outer = new D();

// Instantiating the inner class


D.E inner = outer.new E();
inner.myAbstractMethod();
}
}

Output
Inside abstract method implementation
Observation 8
If a class contains at least one abstract method then compulsory that
we should declare the class as abstract otherwise we will get a
compile-time error ,If a class contains at least one abstract method then,
implementation is not complete for that class, and hence it is not
recommended to create an object so in order to restrict object creation for
such partial classes we use abstract keyword.
Java
/*package whatever //do not write package name here */

import java.io.*;

// here if we remove the abstract


// keyword then we will get compile
// time error due to abstract method
abstract class Demo {
abstract void m1();
}

class Child extends Demo {


public void m1()
{
System.out.print("Hello");
}
}
class GFG {
public static void main(String[] args)
{
Child c = new Child();
c.m1();
}
}

Output
Hello
Observation 9
If the Child class is unable to provide implementation to all abstract
methods of the Parent class then we should declare that Child class as
abstract so that the next level Child class should provide implementation
to the remaining abstract method.
Java
// Java Program to demonstrate
// Observation
import java.io.*;

abstract class Demo {


abstract void m1();
abstract void m2();
abstract void m3();
}

abstract class FirstChild extends Demo {


public void m1() {
System.out.println("Inside m1");
}
}

class SecondChild extends FirstChild {


public void m2() {
System.out.println("Inside m2");
}
public void m3() {
System.out.println("Inside m3");
}
}

class GFG {
public static void main(String[] args)
{
// if we remove the abstract keyword from FirstChild
// Class and uncommented below obj creation for
// FirstChild then it will throw
// compile time error as did't override all the
// abstract methods

// FirstChild f=new FirstChild();


// f.m1();

SecondChild s = new SecondChild();


s.m1();
s.m2();
s.m3();
}
}

Output
Inside m1
Inside m2
Inside m3
In C++, if a class has at least one pure virtual function, then the class
becomes abstract. Unlike C++, in Java, a separate keyword abstract is
used to make a class abstract.
Conclusion
Points to remember from this article are mentioned below:
 An abstract class is a class that cannot be initiated by itself, it needs to
be sub classed by another class to use its properties.
 An abstract class can be created using “abstract” keywords.
 We can have an abstract class without any abstract method.

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

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()
{System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{System.out.println("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
s.draw();
}
}
Output

drawing circle
Another example of Abstract class in java
1. abstract class Bank{
2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
18. }}
Output

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. }
18. }
output
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.

Another real scenario of abstract class


The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
26.
output

I am a
I am b
I am c
I am d

FAQs of Abstract class


1. What is an abstract class in Java?
An abstract class in Java is a class that cannot be initiated on its own but
can be used as a subclass by another class.
2. What is the abstract class purpose?
The main purpose of the abstract class is to create a base class from
which many other classes can be derived.
3. What is the main advantage of abstract class?
An abstract class provides the provides of data hiding in Java.
4. Why abstract class is faster than interface?
An abstract class is faster than an interface because the interface involves
a search before calling any overridden method in Java whereas abstract
class can be directly used.

Difference between Abstract Class and Interface


Points Abstract Class Interface

Cannot be instantiated;
Specifies a set of
contains both abstract
methods a class must
(without implementation)
implement; methods are
and concrete methods
abstract by default.
Definition (with implementation)

Methods are abstract by


Can have both
default; Java 8, can have
implemented and abstract
Implementation default and static
methods.
Method methods.

class can inherit from only A class can implement


Inheritance one abstract class. multiple interfaces.

Access Modifiers Methods and properties Methods and properties


can have any access are implicitly public.
modifier (public, protected,
private).

Can have member Variables are implicitly


variables (final, non-final, public, static, and final
Variables static, non-static). (constants).

You might also like