2

请让我知道这些访问级别在 java 中是否可行,如果不是,有什么替代方案。

问题一:

From same class:                yes
From subclass same package:     yes
From any class same package:    no
From subclass outside package:  no
From any class outside package: no

和问题 2:

From same class:                yes
From subclass same package:     yes
From any class same package:    no
From subclass outside package:  yes
From any class outside package: no

没有一个访问修饰符(public/private/default/protected)提供上述控制集。

例如:我有一个只能在同一个类中访问的私有成员。如我的第一个问题所述,如何对其进行访问控制?

4

7 回答 7

2

没有一个 java 范围符合您的要求

于 2012-09-18T06:36:41.067 回答
1

java 中可用的访问说明符不符合您的要求。

没有区别

From subclass same package:      
From subclass outside package:    
于 2012-09-18T06:40:18.087 回答
0

不同包中的子类不能被赋予单独的访问级别。

唯一可能的解决方法是重新构建包:-(

于 2012-09-18T07:15:29.047 回答
0

你应该可以在这里找到它们:http: //docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

于 2012-09-18T06:25:55.617 回答
0

这种细分应该可以帮助您确定答案。

From same class:                 //private, default, protected, public
From subclass same package:      //default, protected, public
From any class same package:     //default, protected public
From subclass outside package:   //protected, public
From any class outside package:  //public
于 2012-09-18T06:26:03.420 回答
0

不,不可能达到您想要的 2 访问级别要求。

Java 中只有 4 个访问级别,public、default、protected 和 private。它们都不符合您的要求。

于 2012-09-18T06:37:25.310 回答
0

Yes, It's possible. but as mentioned above, it's not achieved by simply using the default available access modifiers. you need to add a getter to control the access to your attribute or method.

package house;

public class Father {
    private String secret = "I am your father";

    // for Q1 use default, for Q2 use protected
    protected String getSecret() {
        if(this.getClass().getName() != "house.Father") return secret;
        else return "some talk about the weather...";
    }
}

This getter allow the access by inheritance exclusively, and a direct access to the private attribute is always available. but the access by reference is denied.

于 2016-12-04T06:27:02.777 回答