簡體   English   中英

為超類指定一個引用java

[英]assigning super class a reference java

我有一個帶有構造函數的Vector類

Vector(int dimension) // creates a vector of size dimension

我有一個類Neuron,它擴展了Vector類

public class Neuron extends Vector {

    public Neuron(int dimension, ... other parameters in here ...) { 
         super(dimension);
         // other assignments below here ...
     }    
}

我希望能夠做的是在Neuron類中為Vector指定另一個Vector的引用。 有點像

    public Neuron(Vector v, ... other parameters in here ...) { 
         super = v;
         // other assignments below here ...
     }    

當然,我不能這樣做。 有一些工作嗎? 即使我無法在Neuron類的構造函數中執行此操作,也許可以。

您需要在Vector類中創建一個復制構造函數

public Vector(Vector toCopy) {
    this.dimension = toCopy.dimension;

    // ... copy other attributes
}

然后在Neuron你做

public Neuron(Vector v, ... other parameters in here ...) { 
     super(v);
     // other assignments below here ...
}

您也可以考慮使用合成而不是繼承 實際上,這是Effective Java中的一個建議。 在這種情況下你會這樣做

class Neuron {
    Vector data;

    public Neuron(Vector v, ... other parameters in here ...) {
        data = v;
        // other assignments below here ...
    }
}

相關問題:

暫無
暫無

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

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