如何从静态上下文中引用非静态方法 [英] How do I refrence a non- static method from a static context

查看:170
本文介绍了如何从静态上下文中引用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数的构造函数,但是当我编译我的主要方法,非静态方法区域不能从静态上下文引用。我知道它的一个简单的修复,我只是不能很好地到那里。感谢

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);
}

和此主要方法

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();     

    }    
}


推荐答案

您需要在类的实例上调用方法。

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

此代码:

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

应为:

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

这篇关于如何从静态上下文中引用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆