this
关键字this的两种形势
this
- 当类中有多个构造方法时,解释引用变量与参数之间的模糊性。
- 当类中有多个构造方法时,用this作为参数传递给另外一个方法。
下面是this使用的两种情况:
public class BirthDate
{
private int month = 4;
private int day = 17;
private int year = 2020;
public BirthDate(int y,int m,int d)
{
this.year = y; // this解释参数的模糊性
this.month = m;
this.day = d;
}
public BirthDate(BirthDay date)
{
this.day = date.day; // this解释参数的模糊性
this.month = date.month;
this.year = date.year;
}
public BirthDate addDays(int add_days) // 构造方法用this作为参数调用
{
BirthDate otherDate = new BirthDate(this);
otherDate.day = otherDay.day + add_days;
return otherDate;
}
}
super
关键字super用于两种情况:
- 获取父类中的变量数据和调用父类中的方法。
- 直接调用父类的构造方法。
下面是super使用的情况:
TestUniversityStudent.java
class Student
{
string name,department;
Student(String name,String deparment) // 定义构造方法
{
this.name = name; //解释参数的模糊性
this.department = department;
}
}
class UniversityStudent extends Student // student的子类
{
String university;
UniversityStudent(String name,String deparment,String university)
{
super(name,department); // 直接调用父类的构造方法
this.umiversity = university //获取父类变量
}
}
public class TestUniversityStudent
{
public static void main(String args[])
{
UniversityStudent s = new UniversityStudent("赵四","计算机科学与技术","华南农业大学珠江学院");
System.out.println("名字"+s.nam+"系"+s.department+"大学"+s.university);
}
}