}
public void setName(String name) { this.name = name; }
public String getSrt() { return srt; }
public void setSrt(String srt) { this.srt = srt; }
public double getMoney() { return money; }
public void setMoney(double money) { this.money = money; }
public double getSrc() { return src; }
public void setSrc(double src) { this.src = src; }
public void info() {
System.out.println(\姓名: \ + this.name); System.out.println(\职称: \ + this.srt); System.out.println(\工资: \ + this.money); System.out.println(\工龄: \ + this.src);
}
public static void main(String[] args) {
Teacher t1 = new Teacher();//教师对象 t1.setName(\张三\); t1.setSrt(\教师\); t1.setMoney(5000); t1.setSrc(5); t1.info();
Teacher t2 = new Teacher();//教师对象 t2.setName(\李四\); t2.setSrt(\助教\);
t2.setMoney(2500); t2.setSrc(1); t2.info(); } }
课程类:
package chapter14;
public class Course {//课程类
private String cNumber;//学科编号 private String cName;//学科名称 private int cUnit;//学科学分
public Course(String cNumber,String cName,int cUnit){//构造方法
this.cName=cName;
this.cNumber=cNumber; this.cUnit=cUnit; }
public void setNumber(String number){ cNumber=number; }
public void setName(String name){ cName=name; }
public void setUnit(int unit){ cUnit=unit; }
public String getNumber(){ return cNumber; }
public String getName(){ return cName; }
public int getUnit(){
return cUnit; }
public void printCourseInfo(){
System.out.println(\学科编号:\+cNumber); System.out.println(\学科名称:\+cName); System.out.println(\学科学分:\+cUnit);
} }
六、实验总结与体会
通过这次实验对类有了更深刻的认识和理解,在面向对象程序设计中,类是有
属性和方法组成的一个程序单元。属性表示了类的数据,而方法表示了类的行为。
被private修饰的属性只能在该类中被调用,不能被其它的类调用,但是通过set和get方法可以使该类的私有属性被其他类调用。
第三题中的教师类中定义了一个空构造方法,课程类中定义了一个有重载的构造方法。构造方法可以在实例化对象的同时对数据成员进行初始化。
在这三个题中对数据成员进行初始化时都使用了this关键字。在java语言中this关键字强调所引用的变量是类的数据成员,所引用的方法是累的成员方法。This的作用有:1.表示类中的数据成员;2.调用本类的构造方法;3.this表示当前对象。