--- title: Abstract Keyword in Java - Scaler Topics description: Abstract in Java is used to achieve abstraction. Topics find Abstract keyword syntax, rules, examples, and more in this article by scaler. author: Aniket Marwade category: Java --- :::section{.main} In Java, the `abstract` keyword facilitates abstraction, which focuses on displaying only relevant details. Abstract classes and methods created using this keyword cannot instantiate objects directly and require inheritance for data extraction. Abstract methods, lacking implementation, are designed for overriding in subclasses. This approach simplifies complex systems by highlighting essential features. ![abstract keyword](https://scaler.com/topics/images/abstract-keyword.webp) ### Syntax ```java abstract class class_name { abstract void method_name(); } ``` ::: :::section{.main} ## Characteristics of Abstract Keyword in Java * Abstract classes cannot be directly instantiated. They serve as templates for other classes to extend from rather than being used independently. * Abstract methods lack a body and are designated with the abstract keyword. They're essentially placeholders for functionality that subclasses must implement. * Subclasses of an abstract class must provide concrete implementations for all abstract methods declared in the parent class. This ensures consistency in functionality across subclasses. * Abstract classes can house both abstract methods and concrete methods. Concrete methods have implementations and are accessible by both the abstract class and its subclasses. Despite not being instantiable, abstract classes can have constructors. * Concrete subclasses invoke these constructors during their instantiation process. Abstract classes can contain instance variables accessible by both the abstract class and its subclasses. * Abstract classes can implement interfaces. This requires the abstract class to provide concrete implementations for all methods defined in the interface. ::: :::section{.main} ## Rules of Abstract Keyword Before using the abstract keyword in Java in your code, you must know some rules. There are some important do's and do n'ts for using abstract keywords. ### Do's : * Only using the abstract keyword in Java with classes and methods is possible. * It is mandatory that classes extending abstract classes implement all the abstract methods of that parent class; otherwise, it should also be declared abstract. * The inner class can be declared abstract by declaring it local. * A static method and constructor can be part of an abstract class. ### Dont's : * The `abstract` keyword cannot be used when the' final' keyword is used. * Abstract methods cannot be declared `private`. * Abstract methods cannot be declared `static`. * An abstract keyword in java cannot be used with variables or constructors. * An abstract class could not have an instance. ::: :::section{.main} ## Abstract Methods in Java *An [abstract method](https://www.scaler.com/topics/abstract-method-in-java/) is an undefined method, the type of method that does not contain any logic or definition but merely a declaration.* You cannot define the body of an abstract method at the time of its declaration. You must end all abstract methods with a semicolon whenever you declare them. You cannot declare abstract methods inside a regular (non-abstract) class; they are always present in abstract classes. Abstract methods serve as templates for abstract classes. The syntax for the abstract method is given below : **Syntax:** ```java abstract return_type method_name (parameters if any); ``` ::: :::section{.main} ## Abstract Classes in Java Abstract classes are restricted classes whose objects cannot be created. You can only access an abstract class by inheriting it from another class. But you must have a question. An [abstract class](https://www.scaler.com/topics/java/abstract-class-in-java/) is largely *undefined*. It consists of abstract methods which are not implemented at all. An abstract class actually serves the purpose of defining the blueprints of classes that are going to inherit from it. *An abstract class has a protected constructor (by default), which only allows derived types to initialize it.* **Syntax:** ```java abstract class class_name { abstract void method_name(); } ``` In the above syntax, an abstract class is declared using the `abstract` keyword, and the method inside it is also an abstract method, which is declared using the `abstract` keyword. Based on the ,above example, let's create a Java program to understand the abstract class. ::: :::section{.main} ## Examples of Abstract Keyword ### Abstract class containing the constructor ```java // abstract class abstract class School { String alert; // Protected constructor School(String alert) { this.alert = alert; } // Abstract method abstract void display(); } class Student extends School { // Instantiate the parent abstract class Student(String alert) { super(alert); } // Override the abstract method @Override void display() { System.out.println(alert); } } public class ConstExample { public static void main(String[] args) { Student obj1 = new Student("Please pay the fees"); obj1.display(); } } ``` **Output:** ```java Please pay the fees ``` **Explanation:** * In the above program, we have an abstract class, School, inside which we have a constructor that initializes a String variable named `alert`. * We also have an abstract method `display()` declared inside the abstract class. * We have another class, Student, which extends the abstract class School. Inside this class, we have a `constructor` for the Student class, which calls the `super` method with a string. * The `display()` method is implemented in the child class `Student`, which prints the value of the `alert` variable. * Now, coming to the `AbstractEg` class, we have made an object of the `Student` class which extends the abstract class `School`; we use that object to call the `display()` method printing **Please pay the fees**. ### Abstract class containing overloaded abstract methods ```java abstract class School { abstract void display(); abstract void display(String alert); } class Student extends School { @Override void display() { System.out.println("Admission is done"); } @Override void display(String alert) { System.out.println(alert); } } public class OverloadedAbstMethods { public static void main(String[] args) { Student obj = new Student(); obj.display(); obj.display("Alert! Please pay the fees"); } } ``` **Output:** ```java Admission is done Alert! Please pay the fees ``` **Explanation:** * In the above program, we have an abstract class called `School` inside, for which we have two overloaded abstract methods named `display()`. * In the first `display()`, the method does not contain parameters, whereas the second one takes one string parameter. * The two abstract methods are overridden in the `Student` class, which inherits from the abstract class `School`. * Now, coming to the driver class `OverloadedAbstMethods`, we have created an object of the `Student` class, which first calls the abstract method, which prints **Admission is made**. * Then while calling the second display method, we pass string value **Alert! Please pay the fees**, which get assigned to the string variable present in the second `display()` method, where we get both the strings as output. ::: :::section{.main} ## Advantages of Abstract Keywords 1. Abstract classes in Java, designated by the 'abstract' keyword, serve to define a standardized interface shared among subclasses. 2. Utilizing abstract classes enables the principle of polymorphism. By declaring a superclass as abstract, a range of subclasses can be treated interchangeably as instances of the superclass. 4. Abstract classes encourage code reuse. By defining common methods and properties, they facilitate the sharing of functionality among multiple subclasses. 5. Enforcing implementation: Abstract methods within abstract classes mandate concrete subclass implementations. This ensures uniform functionality across all subclasses, minimizes errors, and enhances the overall quality of the codebase. 6. Abstract classes facilitate late binding, allowing for dynamic determination of subclass usage during runtime. ::: :::section{.main} ## Abstract and Final Class in Java Before going into the difference between `abstract` and `final`, let's briefly discuss `final` classes. The term **final class** refers to a class that is declared using the **Final** keyword. Using the `final` keyword, you will finalize and close out the implementations of the `methods`, `variables`, and `classes` in this class. After declaring a class as a `final` class, inheriting from that class is impossible. Extending it to another class will give us a `compile-time error` in Java. Also, we could not use `final with abstract` as an abstract class needs to be inherited to implement its methods, whereas final restricts inheritance. **Here is a small implementation of a final class:** ```java //implementation of final class final class One { private int num = 12; } ``` If another class inherits from the final class, it will cause a `compile-time error`. The below code demonstrates this: ```java //implementation of final class //it will cause compile time error final class A { private int num = 12; } //invalid class B extends A { public int val = 100; } public class Main { public static void main(String args[]){ } } ``` The above code will give you the following error: **Output:** ```java Main.java:9: error: cannot inherit from final A class B extends A { ^ 1 error ``` | Abstract Class | Final Class | |:-----------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------------:| | `abstract` keyword is used to declare an abstract class. | `final` keyword is used to declare a final class. | | This helps to achieve abstraction. | This helps to restrict other classes from accessing its properties and methods.| | Abstract classes cannot be instantiated. | It can be instantiated. | | We can inherit an abstract class. | A final class cannot be inherited. | | All abstract classes are meant to be overridden. | There is no concept of overriding in final classes as inheritance is not permitted. | ::: :::section{.summary} ## Conclusion * Abstract keyword is used in Java to achieve Data Abstraction in OOP. * It is only possible to use abstract keywords with classes and methods in Java. * We cannot instantiate an abstract class (though it can have constructors) as it can contain abstract methods that do not have a body. * There is no body in an abstract method. You must end all abstract methods with a semicolon whenever you declare them. * Abstract methods cannot be declared private or static. * Any class that extends an abstract class must implement all of its abstract methods; otherwise, that class must also be declared abstract. * Final classes cannot be inherited, and they cannot contain abstract methods. :::