【问题标题】:Boolean setter wrong output布尔设置器错误输出
【发布时间】:2015-03-24 14:03:14
【问题描述】:

当我在 main 方法中调用 BookClass 时,状态的唯一输出是 truefalse。 为什么它不会在我的 Setter 中打印出 if-else 语句?

public class Book {

private String title;
private int year;
private String author;
private boolean status;

public Book(String title, int year, String author, boolean status){
    this.title = title;
    this.year = year;
    this.author = author;
    this.status = status;
    }

public void setStatus(boolean status){
    this.status = status;   
    if(status){
        System.out.println("Unavailable");
    }
    else{
        System.out.println("Available");
    }
}

【问题讨论】:

  • 你在哪里打电话给setStatus
  • 显示您的main 方法。

标签: java methods boolean output setter


【解决方案1】:

您应该在构造函数中使用函数 setStaus,因为 setter 和 getter 不会隐式工作:

public Book(String title, int year, String author, boolean status){
    this.title = title;
    this.year = year;
    this.author = author;
    setStatus(status);
}

【讨论】:

    猜你喜欢
    • 2017-05-09
    • 2017-04-28
    • 2019-04-21
    • 2022-06-10
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多