4

I have below interface and its implementation class.

Demo.java

public interface Demo{

 void showDemo();

}

DemoImpl.java

@Service
public class DemoImpl implements Demo{

  public void showDemo(){

       //To Do

    }

}

Now i have one class with static method which will internally call showDemo() as below.

DemoStatic.java

@Component
public class DemoStatic{

 @Autowired
 private Demo demo;



     public static void callShowDemo(){

       demo.showDemo(); //calling non static method from static method

       }

}

Here i am calling non static method from static method. Is my design correct? Or do i need to change my design? Please suggest me.

Thanks!

4
  • 2
    You can't call non static method form static method. It will not compile. Commented Nov 13, 2013 at 6:27
  • 1
    Well, you can, but you have to specify which object to call the non-static method on. Commented Nov 13, 2013 at 6:28
  • 1
    In this case, the method call is actually OK; the problem is the reference to the non-static variable demo. There can be multiple instances of DemoStatic, each with its own demo variable. Commented Nov 13, 2013 at 6:30
  • You can just inject the bean and call showDemo() where you need it, no need for static Commented Nov 13, 2013 at 6:33

4 Answers 4

4

You can do it this way

@Component
public class DemoStatic {

 private static Demo demo;

 @Autowired
 public void setDemo(Demo d) {
     demo = d;
 }

  public static void callShowDemo(){
       demo.showDemo(); //calling static method from static method
  }

}
Sign up to request clarification or add additional context in comments.

Comments

3

No your design is not correct.

private Demo demo;

has to be

private static Demo demo;

You just cant use NON static members in a static method

3 Comments

Doltan, if i make Demo variable static then will be there be any issues? Thanks!
no there wont be an issue. But the element is then static and you should know what static means.
The statement should be "You just cant use NON static members in a static method"
0

The above code will not compile at all. You are trying to refer non-static reference from static method, which is not allowed in Java.

Refer this stackoverflow link for better understanding.

Make the following change:

public static Demo demo;

3 Comments

Can Spring autowire static fields?!
@SilviuBurcea : I do not have much expertise in Springs, so cannot comment on that.
0

when you call DemoStatic.callShowDemo(),the demo may not been instand

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.