简体   繁体   English

从另一个类访问私有的最终静态双精度

[英]Accessing Private Final Static Double from Another Class

I am trying to access a private final static double from another class. 我试图从另一个类访问私有的final static double。

Here is the class: 这是班级:

public class coolMath{

private final static double alpha = 5.87;

public coolMath(){

}

public static double calDistance(double x1, double y1, double x2, double y2){
        double dist = Math.sqrt(Math.pow((x2-x1), 2) + Math.pow((y2-y1),2));     
        return dist;
    }

}

I need to access the variable alpha in another class. 我需要在另一个类中访问变量alpha。 Is this possible? 这可能吗? Does something need to happen in the constructor to make it available? 是否需要在构造函数中执行某些操作才能使其可用? Any ideas? 有任何想法吗?

Either make alpha a public field or provide a public static double getAlpha() that returns it. 要么将alpha public static double getAlpha()公共字段,要么提供返回它的public static double getAlpha()

If you make the field public, you access it like so double a = coolMath.alpha . 如果你将该字段double a = coolMath.alpha公共字段,则可以像访问double a = coolMath.alpha一样访问它。

Otherwise, double a = coolMath.getAlpha(); 否则, double a = coolMath.getAlpha();

I strongly suggest you go through java modifiers again. 我强烈建议你再次浏览java修饰符。

This could technically be possible through some esoteric reflection methods, but I highly discourage it. 从技术上讲,这可以通过一些深奥的反思方法来实现,但我强烈反对它。 It's better to change the visibility of your alpha variable or write some method that returns it (or perhaps sets it, if you need that also (but not if your var is final )). 最好改变你的alpha变量的可见性,或者编写一些返回它的方法(或者如果你需要的话也可以设置它(但如果你的var是final话,则设置它))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM