有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java成员、类、可访问性说明

下面是一个我无法理解的例子:

abstract class Personne { 
    protected static int nbPersonnes=0;

    static void nbpersonnes (){
    System.out.println(
    “\n Nombre d’employés :“ + nbPersonnes +
    “\n Nombre de secretaires  : “ + Secretaire.nbSecretaire() +

    }

第二类是Secretaire

class Secretaire extends Personne {        
       private String numBureau;
       private static int nbSecretaires; 
       Secretaire (String nom, String prenom, String rue,String ville,String numBureau) {
          super(nom,prenom,rue,ville);
          this.numBureau=numBureau;
          nbSecretaires++;}

Personne如何访问私有成员Secretaire.nbSecretaire()

我认为类Secretaire可以访问Personne成员,而不是相反nbSecretaires是一个私有成员。如何在课堂之外访问它


共 (2) 个答案

  1. # 1 楼答案

    i thought class Secretaire can access Personne'members, and not the opposite ?

    这在C#中是正确的,但在Java中则不然

    在Java中,同一顶级类中的所有代码都可以访问该顶级类(包括顶级类本身)中声明的所有类的所有私有成员

    JLS 6.6.1

    Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

  2. # 2 楼答案

    Secretaire.nbSecretaire()是一个静态方法调用表达式。它不访问私有nbSecretaire成员,而是访问方法nbSecretaire(),您没有显示其定义

    但是,如果Secretaire类嵌套在Personne中,那么它的所有成员,甚至私有成员,都可以从Personne访问

    注意:在我回答问题时,您发布的代码的语法太混乱,不清楚是否是这种情况