У меня есть подкласс и суперкласс. В подклассе, когда я хочу получить значения суперкласса с super.i и super.one, он показывает нуль. Зачем? Также, когда я расширяю метод суперкласса к подклассу, существует ли абсолютная необходимость вызывать функцию члена суперкласса, используя супер ключевое слово?Доступ к членам суперкласса из подкласса с супер ключевым словом
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;
}
}
Я думаю, что инициализировал значения с помощью конструктора. – xtreak
Как получить доступ к значениям суперкласса, затем? – xtreak
либо изменить имя поля в подклассе, либо инициализировать с помощью super.one, все будет работать. – Batty