例子:
package com.mbyte.easy.admin.www;
/**
* @Author: wqy
* @Date: 2019-06-05 10:20
* @Version 1.0
*/
public class Base {
public int status = 0;
Base(int status){
this.status = status;
System.out.println("执行完父类的构造方法后的status=" + this.status);
}
public void print(){
System.out.println("base");
}
}
=========
package com.mbyte.easy.admin.www;
/**
* @Author: wqy
* @Date: 2019-06-05 10:24
* @Version 1.0
*/
public class Subb extends Base{
public int status;
Subb(int status){
super(status-1);
System.out.println("执行了 super(status-1),status = " + this.status);
this.status = status;
System.out.println("执行了 this.status = status,status = " + this.status);
}
public void printSubb(){
System.out.println("sub");
System.out.println("status=" + status);
}
public void printBase(){
super.print();
System.out.println("status=" + super.status);
}
public static void main(String[] args) {
Subb subb = new Subb(2);
System.out.println("执行了 Subb subb = new Subb(2),status = " + subb.status);
subb.printBase();
subb.printSubb();
}
}
========
结果:
执行完父类的构造方法后的status=1
执行了 super(status-1),status = 0
执行了 this.status = status,status = 2
执行了 Subb subb = new Subb(2),status = 2
base
status=1
sub
status=2
========
this指的是对当前对象的引用,super指的是当前对象里的父对象的引用。当引用当前对象的某个方法或者某个成员时,通常用this。通过super可以调用父类的构造方法、父类的方法和属性。
在Java中,每当创建一个对象后,java虚拟机都会给这个对象分配一个引用自身的指针,这个指针的名字就是this,this是对当前类对象的引用,对象只有被实例化后才存在。
类方法是被static修饰的方法,是不依赖于对象而存在的方法。
所以this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this的用法。