有 Java 编程相关的问题?

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

java我的类定义有什么问题?

这个类为什么不编译

class Exam {

private int score;

    // constructor initializes score to 99
    public  void Exam() {
        score = 99;
    }

    // returns the current value of score
    private int getScore() {
       return score;
    }

    // returns the String representation of the Object
    public String toString() {
        return "The score is " + getScore();
    }
}

共 (6) 个答案

  1. # 1 楼答案

    主要问题是缺少包声明

    package yourpkg;
    
    class Exam {
    

    此外,forExam()上的返回类型使其成为函数而不是构造函数,并将导致警告

  2. # 2 楼答案

    构造函数不需要返回类型。如果删除void,则应该设置

  3. # 3 楼答案

    在构造函数中不使用void

    将构造函数编写为:

    public Exam() { 
        score = 99; 
    } 
    
  4. # 4 楼答案

    只是一个与具体问题无关的建议:

    private int score;
    
    // returns the current value of score
    private int getScore() {
       return score;
    }
    

    如果你想保留private,那么拥有getScore()是没有意义的。让它成为public

    此外,无论何时您想要覆盖某个方法,都要始终使用@Override注释。若你们并没有做到这一点,编译器会让你们知道。这意味着要预防病毒

    例如

    // returns the String representation of the Object
    @Override
    public String toString() {
        return "The score is " + getScore();
    }
    
  5. # 5 楼答案

    构造不应包含void关键字:

    public Exam() {
        score = 99;
    }
    

    构造函数返回新创建对象的引用。但你不必写。所以认为它是void也是错误的

  6. # 6 楼答案

    构造函数不应该有返回类型。甚至不是空的

    public Exam() {
        score = 99;
    }