java中super关键字是什么?
super关键字和this关键字很类似,this可以看做一个引用变量,保存了该对象的地址,是当前对象整体,而super代表的是父类型特征,是子类局部的一些东西,这些继承过来的东西已经在子类里面了,你可以输出整体this,但不能输出父类型特征super。因为super指向的东西不是一个整体,没法打印输出。
与this对比
前提:
this:没有继承也可以使用
super: 只能在继承条件才可以使用
构造方法:
this (): 本类的构造
super(): 父类的构造
super关键字的用法示例
class Account{
private String name;
private int id;
public Account(){
}
public Account(String name,int id) {
this.name=name;
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
class CreditAccount extends Account{
public CreditAccount() {
}
public CreditAccount(String name,int id) {
super(name,id); //super这里的意思是调用父类的构造方法,然后实行初始化属性
}
}
public class supers extends Account{
public static void main(String[] args) {
CreditAccount user = new CreditAccount("lisi",1);
System.out.println(user.getId()+","+user.getName());
}
}
上述代码中的super用于继承了父类型的属性后,对其建立新的值。
评论 (0)