How do I refrence a non- static method from a static context

前端 未结 2 345
花落未央
花落未央 2021-01-26 12:32

I have this constructor with a function however when i compile my main method i non-static method area cannot be referenced from a static context. I know its a simple fix i just

相关标签:
2条回答
  • 2021-01-26 12:49

    You have 2 options.

    1. Make the method static.
    2. Create an instance of the class which implements the method and call the method using the instance.

    Which one to chose is purely a design decision.

    0 讨论(0)
  • 2021-01-26 13:01

    You would need to call the method on an instance of the class.

    This code:

    Rect rect = new Rect (x, y, height, width);
    double area = Rect.area();
    

    Should be:

    Rect rect = new Rect (x, y, height, width);
    double area = rect.area();
                  ^ check here
                    you use rect variable, not Rect class
                    Java is Case Sensitive
    
    0 讨论(0)
提交回复
热议问题