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