非静态方法...不能从静态上下文

问题描述:

这里引用是错误消息非静态方法...不能从静态上下文

non static method hero(double,double,double) cannot be reference from a static context

下面是类方法。

class MyMath { 
    double hero(double n1, double n2, double n3) 
    { 
    double n4; 
    double n5; 
    n4 = (n1 + n2 + n3)/2; 
    n5 = Math.sqrt((n4 * (n4 - n1) * (n4 - n2) * (n4 - n3))); 
    return n5; 
    } 
} 

这里是主程序

static double hero(double n1, double n2, double n3){...} 
+4

[Java - 对非静态字段列表进行静态引用]的可能重复(http://*.com/questions/10200740/java-making-a-static-reference-to-the-non-静态字段列表) – Perception 2012-04-18 06:36:04

你的英雄方法应该放,使其static。否则,只需创建一个MyMath对象并调用该函数。

MyMath m = new MyMath(); 
area_of_triangle = m.hero(length_of_a,length_of_b,length_of_c); //No need to typecast too 

如果你想你的方法hero使用类名被称为

double length_of_a; 
double length_of_b; 
double length_of_c; 
double area_of_triangle; 

area_of_triangle = (double) MyMath.hero(length_of_a,length_of_b,length_of_c); 

,因为您尝试访问MyMath.hero就好像它是一个static方法你得到这个错误。为了解决这个问题,您必须声明方法herostatic或首先创建一个类型为MyMath的对象并从该对象中调用该方法。

您的方法hero不是静态的。这意味着您只能在类MyMath的实例上调用它。您正在尝试调用它,仿佛它是这里的静态方法:

area_of_triangle = (double) MyMath.hero(length_of_a,length_of_b,length_of_c); 

要么使hero方法static,或创建MyMath的实例并调用它的方法。

// Solution 1: Make hero static 
class MyMath { 
    static double hero(double n1, double n2, double n3) 
     // ... 

// Solution 2: Call hero on an instance of MyMath 
MyMath m = new MyMath(); 

area_of_triangle = m.hero(length_of_a,length_of_b,length_of_c); 

注:铸造方法double的结果是没有必要的,该方法已经返回double

您的hero()方法未设置为静态。您可以让hero()像一个静态方法,以便:

static double hero(double n1, double n2, double n3) 
{ 
    ... 

,或者你可以像创建MYMATH的新实例:

MyMath newMath = new MyMath(); 

,然后调用:

newMyMath.hero(length_of_a,length_of_b,length_of_c); 
+0

谢谢Karthik。 V – Hrfpkj 2012-04-18 06:40:38

主要方法是静态的,并且java不允许在静态方法中引用非静态obj。 所以你应该使hero()方法也是静态的,或者从非静态方法引用它。