1.this关键字
package cn.tedu;
/**本类用于复习this关键字和super关键字*/
public class ReviewThis {
public static void main(String[] args) {
/**
* 回顾:
* this:1.区分本类中同名的成员变量和局部变量,this指定本类中的成员变量
* 2.this关键字用来调用构造函数,必须写在构造函数的第一行
*/
cat c = new cat();
c.test();
}
}
class cat{
public cat(){
this(8);
System.out.println("无参构造");
}
public cat(int num) {
this.num = num;
System.out.println("含参构造");
}
int num ;
public void test(){
int num = 10;
System.out.println(num);
System.out.println(this.num);
}
}
2.super关键字
package cn.tedu;
/**本类用于复习super关键字*/
public class ReviewSuper {
public static void main(String[] args) {
/**
* 用法回顾:
* 1.当子类的成员变量与父类的成员变量同名时,用super指定父类的成员变量
* 2.调用父类的构造函数,默认子类在创建对象时会调用父类的构造方法,因为子类构造方法的第一行默认存在super(),
* 子类必须调用父类的一个构造函数
*/
father father = new father("r");
father.test01();
son son = new son();
son.test02();
}
}
class father{
String s = "父类的成员变量s";
public father() {
System.out.println("父类的无参构造");
}
public father(String s) {
this.s = s;
System.out.println("父类的含参构造");
}
public void test01(){
String s = "父类的局部变量s";
System.out.println(s);
System.out.println(this.s);
}
}
class son extends father{
String s = "子类的成员变量s";
public son() {
super("t");
System.out.println("子类的无参构造");
}
public void test02(){
String s = "子类的局部变量s";
System.out.println(s);
System.out.println(this.s);
System.out.println(super.s);
}
}