Even through these reference Tri1
, I am not able to return base value.
public class Triangle {
private double base;
Triangle Tri1 = new Triangle();
public static double getBase()
{
return Tri1.base;
}
}
You can make Tri1
a static variable:
public class Triangle {
private double base;
static Triangle Tri1 = new Triangle();
public static double getBase()
{
return Tri1.base;
}
}
Or make getBase
instance method:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.