Java | Abstract Classes

05 min read

Abstract Class:

It is a class in which one or more methods are declared, but not defined. The bodies of these methods are omitted, as implementing the methods does not make sense. Such methods are called abstract methods, as they have no definition.

Why is an abstract class needed?

Sometimes, a superclass which only defines generalized form needs to be created and that will be shared by all of its subclasses, leaving it to each subclass to fill in the details, without providing the complete implementation of every method. The superclass is created merely to take advantage of polymorphism.

Rules:

  • In order for a subclass to override a.method which has no implementation in the superclass, abstract type modifier can be specified.

Syntax: abstract returntype nameofthemethod(Parameters list);  //no method body

  • An abstract method cannot be private since a private method cannot be inherited and therefore cannot be redefined in the subclass.
  • A class containing one or more abstract methods must be declared abstract.
  • An abstract class cannot be directly instantiated with the new operator (ie., an object cannot be created for an abstract class). If there is a subclass which extends this abstract class) then objects can be created for this.
  • There can be no abstract constructors or abstract static methods.(Because static methods cannot be overridden. Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.)
  • Any subclass of an abstract class must either implement all of the abstract methods in the superclass or be declared abstract itself.
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error