Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overload variables in Java?

I'm writing a class to represent a matrix. I want it to look something like this:

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
}

Is this legal code, or would I have to have different variable names based on the data types that their matrix holds?

like image 657
Rafe Kettler Avatar asked Jul 24 '10 15:07

Rafe Kettler


1 Answers

You can't overload variables. With your approach, you should give them different name, then overload the getMatrix method for different types.

A better approach is to use Java Generics:

public class Matrix<T> {
    private T[][] matrix;
    public T getMatrix() {return matrix;}
    ...
}

and then create objects of whatever types you want: Matrix<Integer>, Matrix<Double>, etc.

like image 139
Amir Rachum Avatar answered Oct 12 '22 16:10

Amir Rachum