簡體   English   中英

使用super關鍵字從子類訪問超類成員

[英]Accessing superclass members from subclass with super keyword

我有一個子類和一個超類。 在子類中,當我想使用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);
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;
        }
}

因為您尚未初始化1,所以默認情況下它的值為零。

hello_weight 

是Box_Weight類的對象,當您調用該類的setValues時,該類中的一個將被擴展,而上一個類將被陰影化 所以超類一個仍然是零。

一個是不是在構造函數初始化。

您不需要super關鍵字即可訪問父類的成員。 但是,您需要做的是具有適當的范圍/可見性。

如果您的父類具有protected字段,而不是private ,則只有子類的成員才能看到它們。

變量的默認范圍是package private. 因此,如果您要訪問父類變量而不是make protected或者將子代和父代都放在同一包中。

在您的情況下, int width, height, depth, i, one; 變量是程序包私有的,因此,如果您的Sub類不在同一程序包之內,則無法訪問。 因此,將它們聲明為protected

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM