【Java入门系列】this、super关键字

this关键字

学习this关键字之前,先来看下对象创建的过程

1、分配对象空间,并将对象成员变量初始化为0或空

2、执行属性值的显示初始化

3、执行构造方法

4、返回对象的地址给相关的变量

本质

this关键字的本质:创建好的对象的地址。由于在构造方法调用前,对象已经创建,在构造方法中可以使用this代表“当前对象”。

用法

1、程序产生二义性的地方,使用this指明当前对象。普通方法中,this指向调用该方法的对象;构造方法中,this指向正要初始化的对象。

2、使用this关键字调用重载的构造方法,避免相同的初始化代码,但只能在构造方法中使用,并且必须位于构造方法中的第一位。

3、this不能用于static方法中。

public class Student {

    public String name;
    
    public int age;
    
    public Student() {
        
    }
    
    public Student(String name) {
        this.name = name;
    }
    
    public Student(String name,int age) {
        this(name);
        this.age = age;
    }
    
    public void study() {
        System.out.println(this.name);
    }
    
    public static void main(String[] args) {
        
        Student student = new Student("小明",20);
        student.study();
        
    }
}

 super关键字

1、super关键字是直接父类对象的引用,可以通过super关键字类访问父类中被子类覆盖的方法和属性。

2、构造方法第一行默认添加super(),调用子类对象构造方法,会默认调用父类的构造方法。

 

posted @ 2018-08-15 18:46  过向往的生活  阅读(127)  评论(0编辑  收藏  举报