Raf*_*ler 6 java variables overloading
我正在写一个代表矩阵的类.我希望它看起来像这样:
public class matrix {
private int[][] matrix;
private double[][] matrix;
//And so on and so forth so that the user can enter any primitive type and
//get a matrix of it
}
Run Code Online (Sandbox Code Playgroud)
这是合法代码,还是我必须根据矩阵所拥有的数据类型使用不同的变量名?
Ami*_*hum 12
你不能重载变量.使用您的方法,您应该为它们指定不同的名称,然后getMatrix为不同类型重载方法.
更好的方法是使用Java Generics:
public class Matrix<T> {
private T[][] matrix;
public T getMatrix() {return matrix;}
...
}
Run Code Online (Sandbox Code Playgroud)
然后创建你想要的任何类型的对象:Matrix<Integer>,Matrix<Double>,等.