×

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract classes are generic classes (or types of objects) used as a basis to create particular objects that conform to its protocol, or the set of operations it supports. Some important points regarding abstract classes
  • An Abstract class is a class that contains abstract as well as concrete methods.
  • An Abstract class can't be instantiated in other words. We cannot create the object of an abstract class.
  • An abstract class is a class that has at least one abstract method, and maybe there can be some regular methods.
  • An abstract class can have static methods and constructors.
  • An abstract class can have final methods which will prevent the subclass from changing the body of the method.
  • We can achieve 0 to 100 percent abstraction using Java abstract classes.
In an object-oriented programming language, classes contain the objects, attributes (properties) and behaviors (methods) which can be based on previously defined classes. Java uses inheritance to derive the specific implementation of abstract classes. When this principle applied for many successions, it creates a hierarchy of classes.  In this situation, abstract classes are at the top and are used to enforce methods that need to be overridden in the subclasses. This process avoids potential runtime errors.

Declaration of abstract class

abstract class Demo
{
abstract method1();
void method2();{
}}

Rules for abstract class

Here are some points that should be remembered before you make an abstract class. We can call them as rules
  • To use an abstract class, we have to inherit it from the other class.
  • To use an abstract class, you need to create another class which extends this class.
  • A class derived from a parent abstract class must contain all the methods of the parent class.
  • The object of the abstract class cannot be created.
  • If the child class does not contain all the method of a parent class, then it should be declared as an abstract class.

Why we need an abstract class?

Let's assume a Student class that contains method info() and its subclasses, name, id etc.. Since every name contains a different id like 'a' contain id 111 and 'b' contains id 222, so there is no point to implement this method to parent class because every child class overrides the method to provide its implementation detail. So when we know that all the student classes will override this, then there is no point to implement this method in the parent class. Thus making this method abstract is a good option. By making this method abstract, we force all the child classes to implement this.

Abstract methods

An abstract method is a method that has only the method definition. An abstract method does not have implementation and body. It defines only the signature of the method. Syntax  abstract void method(double X, double Y); If a class contains at least one abstract method, then it should be declared as abstract. public abstract class Demo{   // declare fields   // declare nonabstract methods   abstract void method();} If an abstract class is subclassed, then subclass will provide the implementation for all abstract method of the parent class. However, if it will not provide the implementation then the subclass must be declared as abstract.

Some scenarios of Abstract class

Example 1
abstract class Food{ 
abstract void eat(); 
} 
//in abstraction, implementation is unknown by end user 
class Pizza extends Food{ 
void eat(){System.out.println("Pizza is fantastic");} 
} 
class Burger extends Food{ 
void eat(){System.out.println("Burger is delicious");} 
} 
//In abstraction, method is called by programmer or user 
class TestAbstraction{ 
public static void main(String args[]){ 
Food obj=new Burger();//In Abstraction, object is provided through method 
obj.eat(); 
} 
} 
Output
Burger is delicious
In the given example, Food is the abstract class and its implementation is provided by the Pizza and Burger classes. Mostly, implementation detail is hidden for us (which is hidden to the end user), and an implementation class object is provided by the factory method. Example 2 This example explains that a Java program may contain an abstract class, an abstract method, method body (non-abstract method), data member, constructor, and even main() method. Have a look at the below example.
abstract class Pc{ 
        Pc(){System.out.println("PC repaired successfully");
        } 
        abstract void performance(); 
        void changeOS(){
     System.out.println("Win 10 installation is successful");
       } 
      } 
     //Creating a Child class which inherits Abstract class 
      class Hp extends Pc{ 
      void performance(){System.out.println("performance is Superb..");} 
      } 
     //Creating a Test class which calls abstract and non-abstract methods 
      class TestAbstraction1{ 
      public static void main(String args[]){ 
       Pc obj = new Hp(); 
       obj.performance(); 
       obj.changeOS(); 
      } 
     }
Output
PC repaired successfully
Performance is Superb..
Win 10 installation is successful

Related Topics

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.