- 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.
- 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.
- package com.instanceofjava.staticinterviewquestions;
- //www.instanceofjava.com
- public class StaticMethodDemo {
- void nonStaticMethod(){
- System.out.println("non static method");
- }
- public static void staticMethod(){
- new StaticMethodDemo().nonStaticMethod();
- }
- public static void main(String[] args) {
- StaticMethodDemo.staticMethod();
- }
- }
Output:
- non static method
No comments