Declare static variables and methods in an abstract class in Java

Java 8Object Oriented ProgrammingProgramming

If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.

A static variable is a class variable. A single copy of the static variable is created for all instances of the class. It can be directly accessed in a static method.

An abstract class in Java is a class that cannot be instantiated. It is mostly used as the base for subclasses to extend and implement the abstract methods and override or access the implemented methods in abstract class.

Example

 Live Demo

abstract class Parent {
   static void display() {
      System.out.println("Static method in an abstract class");
   }
   static int x = 100;
}
public class Example extends Parent {
   public static void main(String[] args) {
      Parent obj = new Example();
      obj.display();
      System.out.print(Parent.x);
   }
}

Output

The output is as follows −

Static method in an abstract class
100
raja
Published on 03-Jan-2019 14:47:09
Advertisements