[英]How to return non-static variable from static method?
Even through these reference Tri1
, I am not able to return base value. 即使通过这些引用
Tri1
,我也无法返回基本值。
public class Triangle {
private double base;
Triangle Tri1 = new Triangle();
public static double getBase()
{
return Tri1.base;
}
}
You can make Tri1
a static variable: 您可以将
Tri1
静态变量:
public class Triangle {
private double base;
static Triangle Tri1 = new Triangle();
public static double getBase()
{
return Tri1.base;
}
}
Or make getBase
instance method: 或制作
getBase
实例方法:
public class Triangle {
private double base;
Triangle Tri1 = new Triangle();
public double getBase()
{
return Tri1.base;
}
}
You can not return instance variable from static method. 您不能从静态方法返回实例变量。
You try to call the private member of a specific object. 您尝试调用特定对象的私有成员。 To access base, you would have to make it static.
要访问基础,您必须将其设置为静态。 But then every triangle has the same base value.
但是,每个三角形都有相同的基值。
public class Triangle {
private double base;
static Triangle Tri1 = new Triangle();
public static double getBase()
{
return Tri1.base;
}
}
Please make above changes. 请进行以上更改。 It runs without error.
它运行没有错误。 Please remember, from static methods, we have access only static members of that class, be it a static variable or another static method.
请记住,从静态方法中,我们只能访问该类的静态成员,无论是静态变量还是其他静态方法。 Static methods are loaded into memory before the non-static members get loaded..so any access of non-static members from static methods looks like you are going to access something that is not created .so you get a compilation error.
静态方法在非静态成员被加载之前已加载到内存中。因此,从静态方法对非静态成员的任何访问似乎都将访问未创建的对象,因此会出现编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.