总结:每个普通方法中都有两个隐式参数:this、super
一:this关键字
Ⅰ:普通方法中,this总是指向调用该方法的对象;
Ⅱ:构造方法中,this总是指向正要初始化的对象;
Ⅲ:this不能用于static方法。
this作为隐式参数,在每个方法中都是作为参数传进去的。super也是一样的道理。
通过this调用其它构造方法的特殊用法:
package com.stduy;
public class Demo6 {
String str;
int num;
public Demo6() {
System.out.println("无参构造方法");
}
public Demo6(String str) {
this.str=str;
System.out.println("参数为str的构造方法");
}
/*
* 在构造方法中通过this调用其它构造方法时,this语句必须放在第一个语句中,位置不能乱
* */
public Demo6(String str,int num) {
//在此构造方法中,通过this调用其它构造方法
this(str);
//this();
this.str=str;
this.num=num;
System.out.println("参数为str、num的构造方法");
}
public static void main(String[] args) {
String str=null;
int num=0;
Demo6 test=new Demo6(str,num);
}
}
二:super关键字
super是直接父类对象的引用,可以通过super来访问父类中被子类覆盖的方法或属性。
对于普通方法:没有顺序限制,可以随便调用
对于构造方法:任何类的构造方法中,第一行都是隐性的调用了super(...);自己加不加都无所谓
public class Demo7 {
public Demo7() {
//super();
System.out.println("执行demo7的构造函数");
}
}
public class Demo7_1 extends Demo7 {
public Demo7_1() {
//super();
System.out.println("执行7_1的构造函数");
}
public static void main(String[] args) {
//Object test=new Object();
Demo7_1 test=new Demo7_1();
}
}
测试结果有没有两个构造方法中的super都是一样的。
执行demo7的构造函数
执行7_1的构造函数
因为所有的类的父类都是object,我们参照object类源码,查看其构造方法为无参构造方法:
public Object() {}
/**
* Returns the runtime class of this {@code Object}. The returned
* {@code Class} object is the object that is locked by {@code
* static synchronized} methods of the represented class.
*
* <p><b>The actual result type is {@code Class<? extends |X|>}
* where {@code |X|} is the erasure of the static type of the
* expression on which {@code getClass} is called.</b> For
* example, no cast is required in this code fragment:</p>
*
* <p>
* {@code Number n = 0; }<br>
* {@code Class<? extends Number> c = n.getClass(); }
* </p>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @jls 15.8.2 Class Literals
*/
这样就能很好的理解继承中各个构造函数的执行顺序了。