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

徘徊边缘 提交于 2019-12-31 05:19:09

问题


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 cant quite get there. Thanks

public class Rect{
     private double x, y, width, height;

     public Rect (double x1, double newY, double newWIDTH, double newHEIGHT){
       x = x1;
       y = newY;
       width = newWIDTH;
       height = newHEIGHT;

    }
    public double area(){
       return (double) (height * width);
}

and this main method

public class TestRect{

    public static void main(String[] args){
        double x = Double.parseDouble(args[0]);
        double y = Double.parseDouble(args[1]);
        double height = Double.parseDouble(args[2]);
        double width = Double.parseDouble(args[3]);
        Rect rect = new Rect (x, y, height, width);
        double area = Rect.area();     

    }    
}

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/25589961/how-do-i-refrence-a-non-static-method-from-a-static-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!