topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- 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. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully