简体   繁体   English

如何从静态方法返回非静态变量?

[英]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.

相关问题 如何从非静态接口方法实现 static 方法? - How to achieve static method from non-static interface method? 如何从 static 方法打印非静态方法? - How to print a non-static method from a static method? 如何从静态上下文引用非静态变量名? - How to reference non-static variable name from static context? 如何从静态上下文中引用非静态方法'findViewById'? - How to reference non-static method 'findViewById' from a static context? 如何从静态调用非静态方法? - How to call non-static method from static? 如何在非静态方法中从另一个类调用非静态方法? (java) - How do I call a non-static method from another class in a non-static method? (java) 如何使用Java 8中的方法引用从非静态类中调用非静态方法? - How to call a non-static method from a non-static class using method reference in Java 8? 在Java中的静态方法中调用非静态方法(非静态变量错误) - Calling non-static method in static method in Java (Non-Static Variable Error) 如何从方法内部编辑实例变量? 不能从静态上下文中引用非静态变量 sum - How to edit instance variable from inside a method? non-static variable sum cannot be referenced from a static context 将非静态返回值合并到静态方法中? - Incorporating a non-static return value into a static method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM