this关键字的作用:
1.调用自己的其他构造方法(需将this放在第一行)
2.代表指向本对象的引用
3.访问本对象的属性或方法
this表示当前对象引用(并不是当前对象),可以借助this来访问对象的字段和方法。
class Person{
private String name;
private int age;
private String sex;
public Person(){
this("bit",12,"man");
//this必须放在无参构造方法的第一行
}
// public Person(){
// this("bit",12);
// }
public Person(String name,int age,String sex){
this.name = name; //该变量是类的成员变量
this.age = age;
this.sex = sex;
}
public Person(String name,int age){
this.name = name;
this.age = age;
}
public void show(){
System.out.println("name: "+name+" age: "+age+" sex: "+sex);
}
}
public class thisDemo {
public static void main(String[] args) {
Person person = new Person();
person.show();
}
}
在构造函数的内部可以使用this关键字,构造函数是用来构造对象的,对象还没有构造好就是用了this,此时this代表的还是当前对象的引用。
super关键字的作用:
1.调用父类的构造方法
2.去访问被隐藏的父类的属性
3.去调用被覆写的父类的方法
super表示获取到父类实例的引用
- 使用了super 来调用父类的构造器
public Bird(String name) {
super(name);
}
- 使用 super 来调用父类的普通方法
class Animal0{
protected String name;
public Animal0(String name){
this.name = name;
}
public void eat(String food){
System.out.println("小动物");
System.out.println(this.name + "正在吃" + food);
}
public void eatingFish(){
System.out.println(this.name + "爱吃鱼");
}
}
public class Cat extends Animal0{
public Cat(String name) {
super(name);
}
public void eat(String food){
System.out.println("我是猫");
System.out.println(this.name + "正在吃" + food);
super.eatingFish();
}
public static void main(String[] args) {
Animal0 animal0 = new Cat("喵");
animal0.eat("大肥鱼");
}
}
super和this的区别
this | super |
---|---|
访问本类中的属性和方法 | 由子类访问父类中的属性和方法 |
先查找本类,如果本类没有就调用父类 | 不查找本类而直接调用父类 |
表示当前对象 | 无 |