3

Can we overload = operator in our class. so that it can behave like String class

I wrote a class in java.

public class Test{
    String name;
}

Now how can i initialize it as below as we do in String class

Test t1 = "abc";
Test t2 = "xyz"

Thanks in advance

Baby
  • 5,062
  • 3
  • 30
  • 52
  • 1
    `= method` ? Are you referring to overloading the `equals()` method ? Or you mean `=` operator overloading ? – Saif Asif May 15 '14 at 05:54
  • However, with has *nothing* to do with operator overloading and there is *no* "= in the String class". Rather, `=` is an assignment operator which is applied *the same* to (and independently of) all types, caveats for autoboxing aside. – user2864740 May 15 '14 at 05:56
  • In Java you have to use `new` to create an object. – Braj May 15 '14 at 05:57
  • @Braj well not always – Scary Wombat May 15 '14 at 05:57
  • 1
    @IwishIcouldthinkofagood I don't want to confuse the OP right now because OP is in learning state and it's not a good time to tell all the possibilities of object creation. – Braj May 15 '14 at 05:58
  • @Braj But in his question he illustrates knowledge of object creation for String without using `new`. – Scary Wombat May 15 '14 at 06:05
  • @IwishIcouldthinkofagood So I have to tell the OP aboutall the other possibilities where `=` is used as object creation. Right? – Braj May 15 '14 at 06:06
  • Hi there. My question is somewhat related to Integer class as well. Before java 5 we use Integer i = new Integer(5); but after that we can use Integer 1=5. Can we achieve the same in our class as well – Amit Kathpal May 15 '14 at 07:19
  • Yes it is true that we can not overload operators in java. But some told me that it can be achieved with native methods. Does some one has any idea about it – Amit Kathpal May 15 '14 at 07:19

3 Answers3

4

You can't do it that way (because of the deliberate missing operator override support - in general, but for assignment as well; see also the difference between String equality in Java == vs .equals()), but you can use a single argument constructor;

public class Test{
  String name;
  public Test(String name) {
    this.name = name;
  }
}

//... Using the constructor.
Test t1 = new Test("abc"); 
Test t2 = new Test("xyz");
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Yes it is true that we can not overload operators in java. But some told me that it can be achieved with native methods. Does some one has any idea about it – Amit Kathpal May 15 '14 at 07:01
0

No, java doesnt support operator overloading unlike C++

Kakarot
  • 4,252
  • 2
  • 16
  • 18
0

No it does not. Check out this blog post to see why.

From that link I am posting the basics.

  • Simplicity and Cleanliness
  • Avoid Programming Errors
  • JVM Complexity
  • Easy Development of Tools

Also check out this SO answer

Community
  • 1
  • 1
geoand
  • 60,071
  • 24
  • 172
  • 190