1-10super和this关键字

什么是super?

super代表的是当前子类对象中的父类型特征。

什么时候使用super?

子类和父类中都有某个数据,例如,子类和父类中都有name这个属性。如果要再子类中访问父类中的name属性,需要使用super。
子类重写了父类的某个方法(假设这个方法名叫m1),如果在子类中需要调用父类中的m1方法时,需要使用super。
子类调用父类中的构造方法时,需要使用super。
注意:super不能用在静态方法中。

例1:

先定义一个Animal类

class Animal {

    public String name = "动物";

    public void eat() {                
        System.out.println("吃饭");
    }

    public void sleep() {            
        System.out.println("睡觉");
    }
}

定义一个Dog类继承Animal

class Dog extends Animal {

    public String name = "旺财";

    public void eat() {                
        System.out.println("吃狗粮");//狗喜欢吃狗粮
    }

    public void m1(){

        System.out.println(super.name);//调用父类中的name变量
        System.out.println(this.name);//可以不加this,系统默认调用子类自己的name
        super.eat();//调用父类中的eat方法
        this.eat();
        //eat();
    }
}

测试类

public class AnimalTest01 {
    public static void main(String[] args) {

        Dog d = new Dog();
        d.m1();
    }
}

例2:

class Animal {

    //颜色
    String color;
    //品种
    String category;

    public Animal(){

        System.out.println("Animal中的构造方法");
    }

    public Animal(String color,String category){

        this.color = color;
        this.category = category;
    }

}

class Dog extends Animal {

    public Dog(){
        super("土豪金","藏獒");//手动调用父类中的有参构造方法给成员变量进行赋值
        System.out.println("Dog中的构造方法");
    }
}

public class Test {
    public static void main(String[] args) {

        Dog d = new Dog();
        System.out.println(d.color);
        System.out.println(d.category);
    }
}

注意:一个构造方法第一行如果没有this(…);也没有显示的去调用super(…);系统会默认调用super();如果已经有this了,那么就不会调用super了,super(…);的调用只能放在构造方法的第一行,只是调用了父类中的构造方法,但是并不会创建父类的对象。

super和this的对比

this和super分别代表什么

this:代表当前对象的引用
super:代表的是当前子类对象中的父类型特征

this和super的使用区别

调用成员变量

this.成员变量: 调用本类的成员变量
super.成员变量: 调用父类的成员变量

调用构造方法

this(…) :调用本类的构造方法
super(…):调用父类的构造方法

调用成员方法

this.成员方法:调用本类的成员方法
super.成员方法:调用父类的成员方法

原文地址:https://www.cnblogs.com/superfly123/p/10443375.html