java中子类调用从父类继承下来的变量一定要加super么?

比如父类里有个int a
子类里调用一定要super.a吗?
直接用a可以吗

如果父类的属性让子类可以访问的话,需要定义成 proected类型。另外,super()是调用父类的构造方法。如果调用父类的属性可以直接a 或者 this.a。

以下是以前写的一个子类继承父类的的demo,你可以参考下。

class Student{
protected String id;
protected String name;
protected double cj;

public Student(String id, String name, double cj){
this.id = id;
this.name= name;
this.cj = cj;
}

public String showStudent(){
return "学号: "+this.id+", 名字: "+this.name+", 成绩: "+this.cj;
}
}

class PostStudent extends Student{
private String direction;

public PostStudent(String id, String name, double cj,String direction){
super( id,  name,  cj);
this.direction = direction;
}

public void setDirection(String d){
this.direction = d;
}
@Override
public String showStudent(){
return this.showStudent()+", 方向: "+this.direction;
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-09-07
在同一包中,super和不用super是一样的,都是只有private不可以访问,其他都可以
相似回答