本帖最后由 gjtdxjd 于 2016-6-20 00:37 编辑
java中的super指的就是父类(super class)
例:B继承A
A类
class A { private String astr;
private String bstr;
public A(string astr, string bstr) {
this.astr = astr; //this指的是本类,在这里就是A
this.bstr = bstr;
}
public String getAstr() {
return this.astr;
}
public String getBstr() {
return this.bstr;
}
}
B类
class B extends A {
private String aa;
private String bb;
public B(String aa, String bb) {
super(aa, bb); //这里就调用了父类的构造方法,给父类的super.astr,super.bstr(super.astr也就是父类的astr变量,super.bstr同理)
//两个变量赋值了,而不是给this.aa,this.bb(this.aa可以理解为本类的aa变量,this.bb同理)赋值
// this.aa = aa;
// this.bb = bb;
}
puplic String getAA() {
return this.aa;
}
public String getBB() {
return this.bb;
}
}
测试类
public class Test {
public static void main(String[] args) {
B b = new B("aabb", "ccdd"); // 调用B的构造方法,给super.astr,super.bstr赋值了
System.out.println(b.getAa()); // null 没有被赋值
System.out.println(b.getBb()); // null
System.out.println(b.getAstr()); // aabb 调用父类的方法,返回super.astr的值
System.out.println(b.getAstr()); // ccdd 调用父类的方法,返回super.bstr的值
}
}
|
|