2

In Apple's programming language Swift, you can use subscript as you do in arrays for your own class. For example a class in Swift could look like this:

class MyNumber {
    let value: Int
    init(value: Int) {
        self.value = value
    }
    subscript(i: Int) -> Int {
        return value * i
    }
}

This class only has a getter subscript but you could do a setter subscript, too. Anyway when doing this:

let number = MyNumber(value: 15)
println(number[3])

it produces the output 45.

Is it possible to write such classes using subscript in Java as well? Of course, I could simply use a method with a parameter but I wanted to know if this is possible. Thanks for any answer :)

1
  • 3
    Nope, not possible. There is no operator overloading in Java. Commented Jan 1, 2015 at 17:11

1 Answer 1

1

Short answer: no. Setting something equal to Class() in Java is creating a new instantiation of that object. Just do something like this:

var = new MyNumber(15)
var.multiply(3)

and in your MyNumber class code, change subscript to multiply for clarity. That will work the same.

A shorthand version of the same principle is

System.out.println(new MyNumber(15).multiply(3));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.