简体   繁体   English

java,在超类中使用构造函数扩展类

[英]java, extending class with constructor in superclass

I have a class that defines field "coordinates" which is an array without length and a subclass where i need to set a length of array to work with it.So the question is how do I change the array of coordinates' length in subclass.我有一个定义字段“坐标”的类,它是一个没有长度的数组和一个子类,我需要设置一个数组的长度来使用它。所以问题是我如何更改子类中坐标数组的长度。 Here is the code: Superclass:这是代码:超类:

abstract class Vector implements sample {       

    private int[] coordinates;  

    public Vector (int[] coordinates) {

    }
}

And subclass :和子类:

class Vector3D extends Vector {

    public Vector3D(int[] coordinates) {
        super(coordinates);

    }
}
abstract class Vector implements sample {       
    private int[] coordinates;  
     public Vector (int[] coordinates){
         this.coordinates=coordinates;
     }
}

If you want to initialize coordinates by calling new Vector3D(1,2,3):如果要通过调用 new Vector3D(1,2,3) 来初始化坐标:

class Vector3D extends Vector {

    public Vector3D(int n1,int n2,int n3) {
       super(new int[]{n1,n2,n3});
   }
}

Your parent class (Vector) needs to set the private field.您的父类(Vector)需要设置私有字段。 Currently, the parameter and the instance variable are unrelated.目前,参数和实例变量是不相关的。

This would do the job:这将完成这项工作:

public abstract class Vector implements Sample {
   private int[] coordinates;

   public Vector(int[] coordinates) {
      this.coordinates = coordinates;
   }
}



public class Vector3D {
   public Vector3D(int[] coordinates) {
      super(coordinates);
   }
}

// usage:
new Vector3D(new int[]{ 1, 2, 3 }); // Vectors coordinate size: 3. Content: 1, 2, 3

This would pass the Vector3Ds array to the parent and its size would be the same, as the one provided to the Vector3D class.这会将 Vector3Ds 数组传递给父级,其大小与提供给 Vector3D 类的大小相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM