- 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
- package com.instanceofjava;
- public class Sample{
- public static void show(){
- System.out.println("show() method called");
- }
- public static void main(String args[]){
- show();
- Sample.show();
- }
- }
- We can also call static method like this but this is not recommended.
Output:
- show() method called
- 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()
- package com.instanceofjava;
- public class SuperDemo{
- public static void show(){
- System.out.println("Super class show() method called");
- }
- }
- package com.instanceofjava;
- public class SubDemo extends SuperDemo{
- public void print(){
- System.out.println("Sub class print() method called");
- }
- public static void main(String args[]){
- SuperDemo.show();
- SubDemo.show();
- }
- }
Output:
- Super class show() method called
- 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.
- package com.instanceofjava;
- public class SuperDemo{
- public static void show(){
- System.out.println("Super class show() method called");
- }
- }
- package com.instanceofjava;
- public class SubDemo extends SuperDemo{
- public static void show(){
- System.out.println("Sub class show() method called");
- }
- public static void main(String args[]){
- SuperDemo.show();
- SubDemo.show();
- }
- }
Output:
- Super class show() method called
- Sub class show() method called
Key points to remember:
No comments