简体   繁体   中英

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?

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.

I think you are looking for Java Generics, a standard Java feature since Java 5.

The idea is that you would have generic Matrix class which can be specialised for any type you need.

There are plenty of tutorials, for example : here

What you have shown is not legal Java code. The approach you suggest (different names) would work, or you could take advantage of Java's object system, and use boxed values (such that the class member is just an Object) or generics, such that the type is a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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