Can I overload variables in Java?

I am 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 do I need to have different variable names based on the data types stored in their matrix?

+5
source share
3 answers

You cannot overload variables. At your approach, you must give them a different name, and then overload the method getMatrixfor different types.

Better use Java Generics:

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

and then create objects of all types Matrix<Integer>, Matrix<Double>etc.

+11
source

I think you're looking for Java Generics, a standard Java feature with Java 5.

, Matrix, , .

, :

+1

What you showed is not legal Java code. The approach you suggest (different names) will work, or you can use the Java object system and use the boxed values ​​(such that the class member is just an object) or generics, so the type is a parameter.

+1
source

All Articles