【发布时间】:2018-06-24 16:25:54
【问题描述】:
我现在正在学习 Java 的继承。我总共有3个问题,感谢您的支持。
第一个问题:我可以在其构造函数中验证类的字段吗?
第二个问题:有人建议我抛出异常进行验证。是指向调用者方法抛出异常还是抛出异常并在构造函数内部处理?
第三个问题:假设该类不是子类,我可以验证代码中显示的字段,而不是使用异常吗?(假设代码不会因为 super() 而产生错误)。
子类
import javax.swing.JOptionPane;
public class Essay extends GradedActivity
{
private final double MAXGRAMMAR = 30;
private final double MAXSPELLING = 20;
private final double MAXLENGTH = 20;
private final double MAXCONTENT = 30;
private double grammar;
private double spelling;
private double length;
private double content;
public Essay(double grammar, double spelling, double length, double content)
{
double total;
while(grammar < 0 || grammar > MAXGRAMMAR)
{
grammar = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid grammar value, try again: "));
this.grammar = grammar;
}
while(spelling < 0 || spelling > MAXSPELLING)
{
spelling = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid spelling value, try again: "));
this.spelling = spelling;
}
while(length < 0 || length > MAXLENGTH)
{
length = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid length value, try again: "));
this.length = length;
}
while(content < 0 || content > MAXCONTENT)
{
content = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid content value, try again: "));
this.content = content;
}
total = grammar + spelling + length + content;
super(total);
}
};
超类
/**
A class that holds a grade for a graded activity.
*/
public class GradedActivity
{
private double score; // Numeric score
/**
The setScore method sets the score field.
@param s The value to store in score.
*/
public void setScore(double s)
{
score = s;
}
/**
The getScore method returns the score.
@return The value stored in the score field.
*/
public double getScore()
{
return score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
@return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}
【问题讨论】:
标签: java validation inheritance constructor