java中this和super关键字的使用

this作用:

1.调用隐式参数;
2.在本类的一个构造器中调用另一个构造器。

super作用:

1.在子类构造器中调用父类的构造器;
2.在子类方法中调用父类的方法。

注意:

1.无论是用this在本类中调用另一个构造器还是用super在子类中调用父类的构造器,该调用语句必须位于语句块的第一句,否则会有“Constructor call must be the first statement in a constructor”报错提示;
2.由第一条可以得出在一个子类的构造器中不能同时调用调用父类的构造器和本类的其他构造器;
3.super调用父类方法时,super关键字只能用在子类非静态方法中,否则“Cannot use super in a static context”报错提示。

package com.zzit.demo;

public class Animal {
    private int leg;

    public Animal() {
        // 根据传入参数的类型、顺序、参数个数判断调用哪一个构造器
        this(2);
    }

    public Animal(int leg) {
        super();// 调用Object类的无参构造
        this.leg = leg;
    }

    public void run() {
        System.out.println("动物跑");
    }

    public int getLeg() {
        return leg;
    }

    public void setLeg(int leg) {
        //this.leg隐式调用对象
        this.leg = leg;
    }

}
package com.zzit.demo;

public class Bird extends Animal {
    public Bird() {
        super(2);// 调用父类带参数的构造方法
    }
    //子类方法中使用了super关键字调用父类方法,该方法不能设置为静态方法
    public void fly() {
        super.run();// 调用父类的run方法
        System.out.println("鸟儿用翅膀飞");// 子类自有方法的描述
    }

    public static void main(String[] args) {
        new Bird().fly();
    }

}

猜你喜欢

转载自blog.csdn.net/liyufu318/article/details/73557061
今日推荐