【问题标题】:What is the problem with my code below? How do I fix the private access error?我下面的代码有什么问题?如何修复私有访问错误?
【发布时间】:2023-01-14 20:36:51
【问题描述】:

你能告诉我如何解决这个问题吗?

class Party {
  private int numGuests;

  public int getnumGuests() {
    return numGuests;
  }

  public void setGuests(int numGuests) {
    this.numGuests = numGuests;
  }

  String displayMessage = "Enjoy the party!";

  {
    System.out.println(displayMessage);
  }
}

public class BirthdayParty extends Party {
  public static void main(String[] args) {
    BirthdayParty bday = new BirthdayParty();
    bday.numGuests = 60;
    bday.setNumGuests(numGuests);
    System.out.println(bday.getNumGuests());

  }
}

     

我希望它打印显示消息和 NumGuests

【问题讨论】:

  • 我建议阅读有关访问修饰符的教程,例如this one over at oracle.com,以及访问器方法(getters 和 setters),例如this one over at baeldung.com
  • 一些评论:下次,请正确格式化您的代码。 --- 为了可读性,建议所有字段都定义在一个类的顶部,而不是分布在整个类中 --- 初始化块应该很少使用,我建议改用构造函数。

标签: java methods subclass encapsulation


【解决方案1】:

你 setter getter 获取和设置私有变量的值

class Party {
    private int numGuests;

    public int getNumGuests() {
        return numGuests;
    }

    public void setNumGuests(int numGuests) {
        this.numGuests = numGuests;
    }

    String displayMessage = "Enjoy the party!";

    {
        System.out.println(displayMessage);
    }
}

class BirthdayParty extends Party {
    public static void main(String[] args) {
       Party bday = new BirthdayParty();
       bday.setNumGuests(60);
       System.out.println(bday.getNumGuests());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多