从单独的类文件访问公共静态类的状态 [英] Access public static class' state from a separate class file

查看:123
本文介绍了从单独的类文件访问公共静态类的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个公共类中有一个公共静态类,如下所示:

I have a public static class within another public class as follows:

public class Foo<A> {
public static class Bar<A>{
    A firstBar;
    Bar(A setBar){
        this.firstBar=setBar;
    }
   }

public final Bar<A> instanceBar;

public Foo(A actualValue) {
    instanceBar = new Bar<A>(actualValue);
}

public Bar<A> getBar() {
    return instanceBar;
}

我的目标是访问 instanceBar 来自不带get方法的单独类文件的状态,并且没有更改 firstBar 的可见性。我如何做到这一点?

My objective is to access instanceBar's state from a separate class file without a get method and without changing the visibility of firstBar. How do I accomplish this?

例如,以下说不可见

public class RetrieveFirstBar {
        public static void main(String[] args) {
             Foo z = new Foo(5l);
             Foo.Bar<Long> z2 = z.getBar();
             long k = z2.firstBar; //not visible!
        }

}

推荐答案

我想你的意思是

class Foo<A>

因为你写的是A firstBar;您提供对变量的包访问权限:
http:// docs .oracle.com / javase / tutorial / java / javaOO / accesscontrol.html

Since you write "A firstBar;" you give package access to the variable: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

如果你在同一个包中有RetrieveFirstBar,你就不会有可见性问题。但是,如果你想从任何地方访问它,你应该写

If you have the RetrieveFirstBar in the same package you will not have visibility problems. But, if you want to access it from everywhere you should write

public A firstBar;

这篇关于从单独的类文件访问公共静态类的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆