Programming





Abstract Class in Java

Abstract Class in Java


by Administrator | 05-Apr-2020
Java

Tags:  Abstract Class  Core Java

Share: 


A class that is defined with an abstract keyword is known as abstract class. If a class has an abstract method then the class should be marked abstact. 

Syntax

abstract class Animal{
   abstract void eat();
} 
  1. Abstract means incomplete implementation. An abstract class can have both abstract and non-abstract/concrete methods. An abstract method is a method that cannot have a body and it must be terminated with semicolon. For e.g.
abstract void doStuff();
  1. By using abstract method, you can force the user to provide a definition.
  2. If a class has at least one abstract method then that class itself should be marked abstract.
  3. Abstract class cannot be instantiated.
  4. The static member(s) of the abstract class can be accessed with the class name using the dot operator.
  5. To access the instance members we need to create an object. Since abstract class cannot be instantiated, you need to define non-abstract sub-class and by using that class’s object the instance member can be accessed. 

Program

abstract class Animal {
    abstract void run();
}
public class Dog extends Animal {
    void run() {
      System.out.println("Dog running.");
    } 
    public static void main(String args[]) {
      Animal animal = new Dog();
      animal.run();
    }
}
Output
Dog running.
  1. All the abstract methods should be overridden by the class extending an abstract class.
  2. Abstract method cannot be marked as static, private, final, or synchronized.

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.