Java 使用super关键字从子类访问超类成员
我有一个子类和一个超类。在子类中,当我想用super.I和super.one检索超类的值时,它显示为零。为什么?另外,当我将超类方法扩展到子类时,是否绝对需要使用super关键字调用超类成员函数Java 使用super关键字从子类访问超类成员,java,inheritance,super,Java,Inheritance,Super,我有一个子类和一个超类。在子类中,当我想用super.I和super.one检索超类的值时,它显示为零。为什么?另外,当我将超类方法扩展到子类时,是否绝对需要使用super关键字调用超类成员函数 public class Inherit{ public static void main(String args[]) { System.out.println("Hello Inheritance!"); Date now = new Date(); System.out.println(now);
public class Inherit{
public static void main(String args[])
{
System.out.println("Hello Inheritance!");
Date now = new Date();
System.out.println(now);
Box hello = new Box(2,3,4);
BoxWeight hello_weight = new BoxWeight(2,5,4,5);
hello.volume();
hello_weight.volume();
Box hello_old = hello;
hello = hello_weight;
//hello.showValues();
hello.show();
hello_old.show();
hello = hello_old;
hello.show();
hello.setValues(7,8);
hello_weight.setValues(70, 80);
hello.showValues();
hello_weight.showValues();
}
}
class Box{
int width, height, depth, i, one;
static int as=0;
Box(int w, int h, int d)
{
++as;
width = w;
height = h;
depth = d;
}
void setValues(int a, int k)
{
i = k;
one = a;
System.out.println("The values inside super are : " + i +" " + one +" " + as);
}
void showValues()
{
System.out.println("The values of BoxWeight : " + i +" " + one);
//System.out.println("The superclass values : "+ super.i + " " + super.one);
}
void volume()
{
System.out.println("Volume : " + width*height*depth);
}
void show()
{
System.out.println("The height : " + height);
}
}
class BoxWeight extends Box{
int weight,i,one;
void volume()
{
System.out.println("Volume and weight : " + width*height*depth +" "+ weight);
}
void setValues(int a, int k)
{
i = k;
one = a;
}
void showValues()
{
System.out.println("The values of BoxWeight : " + i +" " + one);
System.out.println("The superclass values : "+ super.i + " " + super.one);
}
BoxWeight(int w, int h, int d, int we)
{
super(w,h,d);
weight = we;
}
}
因为您还没有初始化一个,所以默认情况下它的值为零
hello_weight
是Box_Weight类的对象,当您调用该类的setValues时,该类的一个被初始化,而超级类一个被阴影化。所以超级类1仍然是零
并且one未在构造函数中初始化。您不需要
super
关键字来访问父类的成员。但是,您需要的是具有适当的范围/可见性
如果父类中的字段受
保护
,而不是私有
,然后,只有子类的成员才能看到它们。变量的默认范围是包私有。
因此,如果要访问父类变量,则make受保护,或者将子类和父类都放在同一个包中
在你的例子中,int宽度,高度,深度,i,1代码>变量是包私有的,因此如果您的子类不在同一个包中,它将无法访问。因此,将它们声明为受保护的
我想我已经使用构造函数初始化了这些值。那么我如何访问超类值呢?要么更改子类中的字段名,要么使用super.one初始化,任何操作都可以。此外,在任何其他类中直接使用字段都是不好的做法,请记住这一点。