Can we call methods of the superclass from a static method in java?

Java 8Object Oriented ProgrammingProgramming

Inheritance can be defined as the process where one (parent/super) class acquires the properties (methods and fields) of another (child/sub). With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties is known as a subclass and the class whose properties are inherited is called superclass.  In short, in inheritance, you can access the members (variables and methods) of the superclass using the subclass object.

Example

 Live Demo

class SuperClass {
   public void display(){
      System.out.println("Hello this is the method of the superclass");
   }
}
public class SubClass extends SuperClass {
   public void greet(){
      System.out.println("Hello this is the method of the subclass");
   }
   public static void main(String args[]){
      SubClass obj = new SubClass();
      obj.display();
      obj.greet();
   }
}

Output

Hello this is the method of the superclass
Hello this is the method of the subclass

Calling superclass methods from a static context

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

Example

 Live Demo

class SuperClass{
   public void display() {
      System.out.println("This is a static method of the superclass");
   }
}
public class SubClass extends SuperClass{
   public static void main(String args[]){
      //Calling methods of the superclass
      new SuperClass().display(); //superclass constructor
      new SubClass().display(); //subclass constructor
   }
}

Output

This is a static method of the superclass
This is a static method of the superclass
raja
Published on 02-Jul-2019 11:49:13
Advertisements