Student class
内容同上
/**
* The Student class keeps track of the following pieces of data
* about a student: the student's name, ID number, the number of
* credits the student has earned toward graduation, and whether
* the student is paid up with respect to university bills.
* All of this information is entirely private to the class.
* Clients can obtain this information only by using the various
* method defined by the class.
*
* @author Leon
*/
public class Student {
/**
* Creates a new Student object with the specified name and ID.
* @param name The student's name as a String
* @param id The student's id as an int
*/
public Student(String name, int id) {
studentName = name;
studentID = id;
}
/**
* Gets the name of this student.
* @return The name of this student
*/
public String getName() {
return studentName;
}
/**
* Gets the id of this student.
* @return The id of this student
*/
public int getId() {
return studentID;
}
/**
* Sets the number of credits earned.
* @param credits The new number of credits earned
*/
public void setCredits(double credits) {
creditsEarned = credits;
}
/**
* Gets the number of credits earned.
* @return The number of credits this student has earned
*/
public double getCredits() {
return creditsEarned;
}
/**
* Sets whether the student is paid up.
* @param flag The value true or flase indicating paid-up status
*/
public void setPaidUp(boolean flag) {
paidUp = flag;
}
/**
* Returns whether the student is paid up.
* @return whether the student is paid up
*/
public boolean isPaidUp() {
return paidUp;
}
/**
* Creates a string identifying this student.
* @return The string used to display this student
*/
public String toString() {
return studentName + " (#" + studentID + ")";
}
/* Public constants */
/** The number of credits required for graduation */
public static final double CREDITS_TO_GRADUATE = 32.0;
/* private instance variables */
private String studentName; /* The student's name */
private int studentID; /* The student's id */
private double creditsEarned; /* The number of credits earned */
private boolean paidUp; /* Whether student is paid up */
}
this 的其他用法
1. 在构造函数中,它使用 this 将对象的创建委托给含有不同参数的其他构造函数.并且,好像是必须放在构造函数的第一行,例如 this(0),表示调用,另一个值有一个参数的构造函数。
2. 用来强调该变量,是类得实例变量。
大部分情况,定义的新类会扩展现有类,让新类继承超类得行为。
构造函数
构造函数流程: 第一步是通过调用 Object构造函数初始化与每个 Object相关的数据,从此,根据继承关系,Java必须调用每个子类级的构造函数。沿着继承向下,一直到该类。
Java 类得每个构造函数都可以通过以下 3 种 方式之一 调用超类构造函数:
如果没有定义类得任何构造函数,Java 会自动定义默认构造函数,就是不接收参数的那种。但是要注意,如果类定义包括构造函数,就不再创建默认构造函数,在这种情况下,所有子类的构造函数必须明确调用其超类里的某个构造函数。
规则是所执行的在层次结构中与对象的实际类最接近的方法。
如果一个类里有两个 public 方法,而你写了一个类继承了该类,那么,当你重新该方法中的一个方法时,有可能因为你的重写而对另一个跟他有联系的public 方法出现问题,这种情况很快会给维护带来极大的麻烦,所以,在现有类里重写方法时要小心,因为新的定义可能不符合原始类所作的假设,作为一般规则,只有当这些方法的文档特别要求这样做时才重写方法。有时类得设计师提出可以重写该方法,这样的情况,还可以考虑。保守使用重写