YouTip LogoYouTip

Java Abstraction

Java Abstract Classes | Tutorial

Tutorial -- Learning not just technology, but dreams!

Java Tutorial

Java Tutorial Java Introduction Java Development Environment Setup Java Basic Syntax Java Comments Java Objects and Classes Java Basic Data Types Java Variable Types Java Variable Naming Rules Java Modifier Types Java Operators Java Loop Structures – for, while and do…while Java Conditional Statements – if…else Java switch case Statement Java Number & Math Class Java Character Class Java String Class Java StringBuffer and StringBuilder Class Java Arrays Java Date and Time Java Regular Expressions Java Methods Java Constructors Java Stream, File and IO Java Scanner Class Java Exception Handling

Java Object-Oriented Programming

Java Inheritance Java Override/Overload Java Polymorphism Java Abstract Classes Java Encapsulation Java Interfaces Java Enums Java Packages Java Reflection

Java Advanced Tutorial

Java Data Structures Java Collections Framework Java ArrayList Java LinkedList Java HashSet Java HashMap Java Iterator Java Object Java NIO Files Java Generics Java Serialization Java Networking Java Sending Email Java Multithreading Java Applet Basics Java Documentation Comments Java Examples Java 8 New Features Java MySQL Connection Java 9 New Features Java Quiz Java Common Libraries

Java Polymorphism

Java Encapsulation

Deep Dive

  • Scripting Languages
  • Java (Programming Language)
  • Computer Science
  • Social Sciences
  • Science
  • Programming
  • Java
  • java
  • Language Resources
  • Machine Learning and Artificial Intelligence

Java Abstract Classes


In object-oriented programming, all objects are depicted by classes. However, conversely, not all classes are used to depict objects. If a class does not contain enough information to depict a concrete object, such a class is called an abstract class.

Abstract classes retain all other functionalities of a class except that they cannot be instantiated. Member variables, member methods, and constructors are accessed in the same way as in regular classes.

Since abstract classes cannot be instantiated, they must be inherited to be used. This is also why the decision to design an abstract class is usually made during the design phase.

The parent class contains common methods of the subclass collection, but since the parent class itself is abstract, these methods cannot be used directly.

In Java, an abstract class represents an inheritance relationship. A class can only inherit one abstract class, but a class can implement multiple interfaces.


Abstract Class

In Java, the abstract keyword is used to define an abstract class. Consider the following example:

Employee.java File Code:

/* File name : Employee.java */
public abstract class Employee
{
   private String name;
   private String address;
   private int number;

   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }

   public double computePay()
   {
     System.out.println("Inside Employee computePay");
     return 0.0;
   }

   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name + " " + this.address);
   }

   public String toString()
   {
      return name + " " + address + " " + number;
   }

   public String getName()
   {
      return name;
   }

   public String getAddress()
   {
      return address;
   }

   public void setAddress(String newAddress)
   {
      address = newAddress;
   }

   public int getNumber()
   {
     return number;
   }
}

Notice that the Employee class is not much different. Although it is an abstract class, it still has 3 member variables, 7 member methods, and 1 constructor. Now, if you try the following example:

AbstractDemo.java File Code:

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String[] args)
   {
      /* Following is not allowed and will throw error */
      Employee e = new Employee("George W.", "Houston, TX", 43);

      System.out.println("n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}

When you try to compile the AbstractDemo class, you will get the following error:

Employee.java:46: Employee is abstract; cannot be instantiated
      Employee e = new Employee("George W.", "Houston, TX", 43);
                   ^
1 error

Inheriting Abstract Classes

We can inherit the properties of the Employee class as follows:

Salary.java File Code:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary

   public Salary(String name, String address, int number, double salary)
   {
      super(name, address, number);
      setSalary(salary);
   }

   public void mailCheck()
   {
      System.out.println("Within mailCheck of Salary class ");
      System.out.println("Mailing check to " + getName() + " with salary " + salary);
   }

   public double getSalary()
   {
      return salary;
   }

   public void setSalary(double newSalary)
   {
      if(newSalary >= 0.0)
      {
         salary = newSalary;
      }
   }

   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Although we cannot instantiate an object of the Employee class, if we instantiate a Salary class object, the object will inherit the 7 member methods from the Employee class, and through these methods, we can set or get the three member variables.

AbstractDemo.java File Code:

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String[] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

      System.out.println("Call mailCheck using Salary reference --");
      s.mailCheck();

      System.out.println("n Call mailCheck using Employee reference--");
      e.mailCheck();
   }
}

The output of the above program is as follows:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Abstract Methods

If you want to design a class that contains a special member method whose implementation is determined by its subclasses, you can declare that method as an abstract method in the parent class.

The abstract keyword can also be used to declare abstract methods. An abstract method contains only the method name and no method body.

An abstract method has no definition. The method name is followed directly by a semicolon, not curly braces.

public abstract class Employee
{
   private String name;
   private String address;
   private int number;

   public abstract double computePay();

   // Rest of the code
}

Declaring an abstract method results in the following two consequences:

  • If a class contains an abstract method, then that class must be an abstract class.
  • Any subclass must override the abstract method of the parent class, or declare itself as an abstract class.

A subclass inheriting an abstract method must override that method. Otherwise, the subclass must also be declared as an abstract class. Ultimately, a subclass must implement the abstract method; otherwise, from the initial parent class to the final subclass, none can be used to instantiate objects.

If the Salary class inherits the Employee class, it must implement the computePay() method:

Salary.java File Code:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; // Annual salary

   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }

   // Rest of the code
}

Summary of Abstract Class Rules

  1. Abstract classes cannot be instantiated (a common mistake for beginners). If instantiated, an error will occur, and compilation will fail. Only non-abstract subclasses of an abstract class can create objects.
  2. An abstract class does not necessarily contain abstract methods, but a class with abstract methods must be an abstract class.
  3. Abstract methods in an abstract class are only declarations and do not contain a method body, meaning the specific implementation or functionality of the method is not provided.
  4. Constructors and class methods (methods modified with static) cannot be declared as abstract methods.
  5. The subclass of an abstract class must provide a concrete implementation of the abstract methods in the abstract class, unless the subclass is also an abstract class.

Java Polymorphism

Java Encapsulation

iFlytek Xingchen Coding Plan includes free model call quotas, DeepSeek, GLM, Kimi, MiniMax, one-stop experience and deployment platform. Configuration Guide Β₯3.9/ month Subscribe Now

5 Notes Write a Note

  1. #0 tianqixin
    429***967@qq.com
    Reference Address
← Java EncapsulationJava Polymorphism β†’