×

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

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.