一、this使用场景之构造方法时间的相互调用
this():调用本类中无参的构造方法
this(...):调用本类中有参的构造方法
并且只能在构造方法中使用this+()的使用方式,并且必须是第一句
二、this作为返回值和参数
public class Student {
public Student() {
super();
}
public Student(String name) {
super();
}
public Student(String name, int age) {
this(name);//构造方法之间的调用
}
public Student getStudent() {
return this;//作为返回值
}
public void setStudent(Student stu) {
}
public void useStdent() {
setStudent(new Student());
setStudent(this);//作为参数传递
}
}
三、方法覆写注意事项
1、私有方法不能被覆写
2、static修饰的方法不能被覆写
3、方法签名要一致
4、访问权限不能小于父类
5、返回值类型可以和父类一致或者是父类返回类型的子类
class Person{
public Object motion(){
return new Person();
}
}
public class Student extends Person {
@Override
public String motion() {
return "测试";
}
}
6、@Override一定要加上
四、== 和 equals 的区别
1、== 用于基本数据类型的比较,就是直接比较值的大小;用于引用数据类型,则是比较对象在堆中的地址(对应栈中的值)是否相同,是否引用同一个对象。
2、equals不能比较基本数据类型,只能用于引用数据类型,而其源码使用的依然是 == ,因此在实际使用过程中会根据项目需求来覆写Object类中的equals。
3、特别注意:在包装类中,Integer(-128——127)范围内,其对象用==判断值是否相等,相当于基本数据类型的值判断,而超出这个范围,则为对象地址判断。
public class Test {
public static void main(String args[]){
Integer a1 = 128;
Integer a2 = 128;
System.out.println(a1==a2);//false
Integer b1 = -128;
Integer b2 = -128;
System.out.println(b1==b2);//true
}
}