» » » Calling static method from non static method in java

  • Static means class level and non static means object level.
  • Non static variable gets memory in each in every object dynamically.
  • Static variables are not part of object and while class loading itself all static variables gets memory.
  • Like static variables we have static methods. Without creating object we can access static methods.
  • Static methods are class level. and We can still access static methods in side non static methods.
  • We can call static methods without using object also by using class name.
  • And the answer to the question of  "is it possible to call static methods from non static methods in java" is yes.
  • If we are calling a static method from non static methods means calling a single common method using unique object of class which is possible. 


Program #1: Java example program to call static method from non static method.


  1. package com.instanceofjava.staticinterviewquestions;
  2. public class StaticMethodDemo {
  3.  
  4. void nonStaticMethod(){
  5.         
  6.         System.out.println("Hi i am non static method");
  7.         staticMethod();
  8.  }
  9.     
  10.  public static void staticMethod(){
  11.         
  12.         System.out.println("Hi i am static method");
  13.   }
  14.     
  15.  public static void main(String[] args) {
  16.         StaticMethodDemo obj= new StaticMethodDemo();
  17.         
  18.         obj.nonStaticMethod();
  19.  
  20.     }
  21.  
  22. }
 Output:

  1. Hi i am non static method
  2. Hi i am static method

  • In the above program we have created object of the class and called a non static method on that object and in side non static method called a static method.
  • So it is always possible to access static variables and static methods in side non static methods

 Program #2: Java example program to call static method from non static method.


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