Java访问器中的类

时间:2014-09-07 11:18:16

标签: java

考虑以下代码:

package question.pkg2;

public class Car {

    private int wheels;
    private String color;
    private boolean roadworthy;
    public int year = 1982;

    public Car() {

    }

    public Car(int numberOfWheels, String color, boolean roadworthy, int yearOfManufactured) {
        wheels = numberOfWheels;
        this.color = color;
        this.roadworthy = roadworthy;
        year = yearOfManufactured;

    }

    public int getNumberOfWheels() {
        return wheels;
    }

    public String getColor() {
        return color;

    }

    public String changeColor() {
        return color;

    }

    public boolean getRoadworthiness() {
        return roadworthy;
    }

    public String getYear(int checkYear) {
        if (year < 1982) {
            year = checkYear;
            System.out.println("it is not considered roadworthy");
        }

    }
}

我的问题是要检查一年,但我收到了错误声明,这是什么意思?#34;缺少退货声明&#34;?

3 个答案:

答案 0 :(得分:1)

您的方法签名是

public String getYear(int checkYear)

因此,您需要返回nullString

这是你需要考虑的事情:

  • 你的方法是“getYear”,所以String是一个正确的返回类型吗?
  • 您正在修改“getSomething”方法中的字段,这可能会导致混淆。
  • 您有一个roadworthy字段,而在getYear中,它会打印与“适于行驶”相关的消息;如果在year中更改getYear,是否还应更新roadworthy

答案 1 :(得分:0)

你的方法:

public String getYear(int checkYear) {
    if (year < 1982) {
        year = checkYear;
        System.out.println("it is not considered roadworthy");
    }

}

如果希望该方法将年份作为String返回,则需要将int转换为String 所以它必须是这样的:

public String getYear(int checkYear) {
    if (year < 1982) {
        year = checkYear;
        System.out.println("it is not considered roadworthy");
    }
    return Integer.toString(year);
}

或者,如果你只是想要写一个consol,如果年&lt; 1982年 所以它必须是这样的:

public void getYear(int checkYear) {
    if (year < 1982) {
        year = checkYear;
        System.out.println("it is not considered roadworthy");
    }
}

答案 2 :(得分:0)

您在getYear方法中缺少返回值。当您使用void之外的返回类型对某些方法进行十分转换时,必须始终从该方法返回一个cpmpatible值。否则你会得到那个错误。

public String getYear(int checkYear) {
       if (year < 1982) {
            year = checkYear;
            System.out.println("it is not considered roadworthy");
       }
       return "some string value that you want to return"; 
}