Java基础- super 和 this 解析

1. superkeyword表示超(父)类的意思。this变量代表对象本身。

2. super訪问父类被子类隐藏的变量或覆盖的方法。当前类假设是从超类继承而来的,当调用super.XX()就是调用基类版本号的XX()方法。


当中超类是近期的父类。

3.调用super() 父类构造函数的时候仅仅能调用在子类构造函数的第一行

4.this仅仅能在类中的非静态方法中使用。静态方法和静态的代码块中绝对不能出现this,这在“Javakeywordstatic、final使用总结”一文中给出了明白解释。

而且this仅仅和特定的对象关联,而不和类关联,同一个类的不同对象有不同的this

列子:

class Person {
    protected void print() {
       System.out.println("The print() in class Person.");
    }
}
 
public class DemoSuper extends Person {

    public DemoSuper(){

       super(); //调用父类的构造方法。并且放第一行。假设不写,系统自己主动加
    }
    public void print() {
       System.out.println("The print() in class DemoSuper.");
       super.print();// 调用父类的方法
    }
 
    public static void main(String[] args) {
       DemoSuper ds = new DemoSuper();
       ds.print();
    }
}



原文地址:https://www.cnblogs.com/mfmdaoyou/p/6748236.html