» » » How to call non static method from static method java

  • Class is a template and when we create object instance variables gets memory.
  • If we create two objects variables get memory in two objects. So instance variables gets memory whenever object is created.
  • When we create variables as static , memory will not be created in objects because static means class level and it belongs to class not object but we can access static variables and static methods from objects.
  • Calling static method from non static method in java 
  • In our scenario calling a non static method from static method in java.
  • If we are calling a non static method then we need to use object so that it will call corresponding object non static method.
  • Non static methods will be executed or called by using object so whenever we want to call a non static method from static method we need to create an instance and call that method.
  • If we are calling non static method directly from a static method without creating object then compiler throws an error. 



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


calling non static method from static method.png

  • In the above program we are trying to call non static method of class from a static method so compiler throwing error.
  • Can not make a static reference to the non- static method nonStaticMethod() from the type StaticMethodDemo
  • So without object we can not cal non static method of a class.
  • Check the below example program calling non static method from static method by creating object of that class and on that object calling non static method.

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

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

  1. 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