• If you want to call static method of a class we can call directly from another static method or by using its class name we can call static method of that class.
  • let us see a program on how to call a static method of a class

  1. package com.instanceofjava;
  2. public class Sample{

  3. public static void show(){
  4.  
  5.  System.out.println("show() method called");
  6.  
  7. }
  8.  public static void main(String args[]){
  9.  
  10.  show();
  11. Sample.show();
  12.  
  13. }
  14. }

  • We can also call static method like this but this is not recommended.

static method in java interview questions




 Output:
  1. show() method called
  2. show() method called

  • Now our question is can we call super class static method from sub class?
  • Yes we can call super class static method inside sub class using super_class_method();
  • We can also call super class static method using Sub_class_name.superclass_staticMethod()


  1. package com.instanceofjava;
  2.  
  3. public class SuperDemo{

  4. public static void show(){
  5.  
  6.   System.out.println("Super class show() method called");
  7.  
  8. }
  9.  
  10. }



  1. package com.instanceofjava;
  2. public class SubDemo extends SuperDemo{

  3. public void print(){
  4.  
  5.  System.out.println("Sub class print() method called");
  6.  
  7. }
  8.  public static void main(String args[]){
  9.  
  10. SuperDemo.show();
  11. SubDemo.show();
  12. }
  13. }

Output:
  1. Super class show() method called
  2. Super class show() method called

  • If the same static method defined in sub class also then we can not call super class method using sub class name if we call them sub class static method will be executed.

  1. package com.instanceofjava;
  2.  
  3. public class SuperDemo{

  4. public static void show(){
  5.  
  6.   System.out.println("Super class show() method called");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. public class SubDemo extends SuperDemo{

  3. public static void show(){
  4.  
  5.   System.out.println("Sub class show() method called");
  6.  
  7. }
  8.  public static void main(String args[]){
  9.  
  10. SuperDemo.show();
  11. SubDemo.show();
  12. }
  13. }

 Output:
  1. Super class show() method called
  2. Sub class show() method called

Key points to remember:
  1. Can we Overload static methods in java
  2. Can we Override static methods in java

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu