Why doesnt Java offer operator overloading

Mistake producing Gemini contented Question & Answer :

Coming from C++ to Java, the apparent unanswered motion is wherefore didn’t Java see function overloading?

Isn’t Analyzable a, b, c; a = b + c; overmuch easier than Analyzable a, b, c; a = b.adhd(c);?

Is location a identified ground for this, legitimate arguments for not permitting function overloading? Is the ground arbitrary, oregon mislaid to clip?

Location are a batch of posts complaining astir function overloading.

I felt I had to make clear the “function overloading” ideas, providing an alternate viewpoint connected this conception.

Codification obfuscating?

This statement is a fallacy.

Obfuscating is imaginable successful each languages…

It is arsenic casual to obfuscate codification successful C oregon Java done features/strategies arsenic it is successful C++ done function overloads:

// C++ T function + (const T & a, const T & b) // adhd ? { T c ; c.worth = a.worth - b.worth ; // subtract !!! instrument c ; } // Java static T adhd (T a, T b) // adhd ? { T c = fresh T() ; c.worth = a.worth - b.worth ; // subtract !!! instrument c ; } /* C */ T adhd (T a, T b) /* adhd ? */ { T c ; c.worth = a.worth - b.worth ; /* subtract !!! */ instrument c ; } 

…Equal successful Java’s modular interfaces

For different illustration, fto’s seat the Cloneable interface successful Java:

You are expected to clone the entity implementing this interface. However you might prevarication. And make a antithetic entity. Successful information, this interface is truthful anemic you may instrument different kind of entity altogether, conscionable for the amusive of it:

people MySincereHandShake implements Cloneable { national Entity clone() { instrument fresh MyVengefulKickInYourHead() ; } } 

Arsenic the Cloneable interface tin beryllium abused/obfuscated, ought to it beryllium banned connected the aforesaid grounds C++ function overloading is expected to beryllium?

We might overload the toString() technique of a MyComplexNumber people to person it instrument the stringified hr of the time. Ought to the toString() overloading beryllium banned, excessively? We may sabotage MyComplexNumber.equals to person it instrument a random worth, modify the operands… and many others. and so on. and so forth..

Successful Java, arsenic successful C++, oregon any communication, the programmer essential regard a minimal of semantics once penning codification. This means implementing an adhd relation that provides, and Cloneable implementation technique that clones, and a ++ function that increments.

What’s obfuscating anyhow?

Present that we cognize that codification tin beryllium sabotaged equal done the pristine Java strategies, we tin inquire ourselves astir the existent usage of function overloading successful C++?

Broad and earthy notation: strategies vs. function overloading?

We’ll comparison beneath, for antithetic instances, the “aforesaid” codification successful Java and C++, to person an thought of which benignant of coding kind is clearer.

Earthy comparisons:

// C++ examination for constructed-ins and person-outlined sorts bool isEqual = A == B ; bool isNotEqual = A != B ; bool isLesser = A < B ; bool isLesserOrEqual = A <= B ; // Java examination for person-outlined varieties boolean isEqual = A.equals(B) ; boolean isNotEqual = ! A.equals(B) ; boolean isLesser = A.comparesTo(B) < zero ; boolean isLesserOrEqual = A.comparesTo(B) <= zero ; 

Delight line that A and B might beryllium of immoderate kind successful C++, arsenic agelong arsenic the function overloads are offered. Successful Java, once A and B are not primitives, the codification tin go precise complicated, equal for primitive-similar objects (BigInteger, and so forth.)…

Earthy array/instrumentality accessors and subscripting:

// C++ instrumentality accessors, much earthy worth = myArray[25] ; // subscript function worth = myVector[25] ; // subscript function worth = myString[25] ; // subscript function worth = myMap["25"] ; // subscript function myArray[25] = worth ; // subscript function myVector[25] = worth ; // subscript function myString[25] = worth ; // subscript function myMap["25"] = worth ; // subscript function // Java instrumentality accessors, all 1 has its particular notation worth = myArray[25] ; // subscript function worth = myVector.acquire(25) ; // methodology acquire worth = myString.charAt(25) ; // technique charAt worth = myMap.acquire("25") ; // technique acquire myArray[25] = worth ; // subscript function myVector.fit(25, worth) ; // methodology fit myMap.option("25", worth) ; // methodology option 

Successful Java, we seat that for all instrumentality to bash the aforesaid happening (entree its contented done an scale oregon identifier), we person a antithetic manner to bash it, which is complicated.

Successful C++, all instrumentality makes use of the aforesaid manner to entree its contented, acknowledgment to function overloading.

Earthy precocious sorts manipulation

The examples beneath usage a Matrix entity, recovered utilizing the archetypal hyperlinks recovered connected Google for “Java Matrix entity” and “C++ Matrix entity”:

// C++ YMatrix matrix implementation connected CodeProject // http://www.codeproject.com/KB/structure/ymatrix.aspx // A, B, C, D, E, F are Matrix objects; E = A * (B / 2) ; E += (A - B) * (C + D) ; F = E ; // heavy transcript of the matrix // Java JAMA matrix implementation (earnestly...) // http://mathematics.nist.gov/javanumerics/jama/doc/ // A, B, C, D, E, F are Matrix objects; E = A.occasions(B.occasions(zero.5)) ; E.plusEquals(A.minus(B).instances(C.positive(D))) ; F = E.transcript() ; // heavy transcript of the matrix 

And this is not constricted to matrices. The BigInteger and BigDecimal courses of Java endure from the aforesaid complicated verbosity, whereas their equivalents successful C++ are arsenic broad arsenic constructed-successful varieties.

Earthy iterators:

// C++ Random Entree iterators ++it ; // decision to the adjacent point --it ; // decision to the former point it += 5 ; // decision to the adjacent fifth point (random entree) worth = *it ; // will get the worth of the actual point *it = three.1415 ; // units the worth three.1415 to the actual point (*it).foo() ; // call technique foo() of the actual point // Java ListIterator<E> "bi-directional" iterators worth = it.adjacent() ; // decision to the adjacent point & instrument the worth worth = it.former() ; // decision to the former point & instrument the worth it.fit(three.1415) ; // units the worth three.1415 to the actual point 

Earthy functors:

// C++ Functors myFunctorObject("Hullo Planet", forty two) ; // Java Functors ??? myFunctorObject.execute("Hullo Planet", forty two) ; 

Matter concatenation:

// C++ watercourse dealing with (with the << function) stringStream << "Hullo " << 25 << " Planet" ; fileStream << "Hullo " << 25 << " Planet" ; outputStream << "Hullo " << 25 << " Planet" ; networkStream << "Hullo " << 25 << " Planet" ; anythingThatOverloadsShiftOperator << "Hullo " << 25 << " Planet" ; // Java concatenation myStringBuffer.append("Hullo ").append(25).append(" Planet") ; 

Fine, successful Java you tin usage MyString = "Hullo " + 25 + " Planet" ; excessively… However, delay a 2nd: This is function overloading, isn’t it? Isn’t it dishonest???

:-D

Generic codification?

The aforesaid generic codification modifying operands ought to beryllium usable some for constructed-ins/primitives (which person nary interfaces successful Java), modular objects (which might not person the correct interface), and person-outlined objects.

For illustration, calculating the mean worth of 2 values of arbitrary varieties:

// C++ primitive/precocious varieties template<typename T> T getAverage(const T & p_lhs, const T & p_rhs) { instrument (p_lhs + p_rhs) / 2 ; } int intValue = getAverage(25, forty two) ; treble doubleValue = getAverage(25.25, forty two.forty two) ; analyzable complexValue = getAverage(cA, cB) ; // cA, cB are analyzable Matrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix // Java primitive/precocious sorts // It received't truly activity successful Java, equal with generics. Bad. 

Discussing function overloading

Present that we person seen just comparisons betwixt C++ codification utilizing function overloading, and the aforesaid codification successful Java, we tin present discourse “function overloading” arsenic a conception.

Function overloading existed since earlier computer systems

Equal extracurricular of machine discipline, location is function overloading: For illustration, successful arithmetic, operators similar +, -, *, and many others. are overloaded.

So, the signification of +, -, *, and so on. modifications relying connected the sorts of the operands (numerics, vectors, quantum movement capabilities, matrices, and so on.).

About of america, arsenic portion of our discipline programs, realized aggregate significations for operators, relying connected the varieties of the operands. Did we discovery them complicated, past?

Function overloading relies upon connected its operands

This is the about crucial portion of function overloading: Similar successful arithmetic, oregon successful physics, the cognition relies upon connected its operands’ varieties.

Truthful, cognize the kind of the operand, and you volition cognize the consequence of the cognition.

Equal C and Java person (difficult-coded) function overloading

Successful C, the existent behaviour of an function volition alteration in accordance to its operands. For illustration, including 2 integers is antithetic than including 2 doubles, oregon equal 1 integer and 1 treble. Location is equal the entire pointer arithmetic area (with out casting, you tin adhd to a pointer an integer, however you can’t adhd 2 pointers…).

Successful Java, location is nary pointer arithmetic, however person inactive recovered drawstring concatenation with out the + function would beryllium ridiculous adequate to warrant an objection successful the “function overloading is evil” creed.

It’s conscionable that you, arsenic a C (for humanities causes) oregon Java (for individual causes, seat beneath) coder, you tin’t supply your ain.

Successful C++, function overloading is not non-compulsory…

Successful C++, function overloading for constructed-successful sorts is not imaginable (and this is a bully happening), however person-outlined varieties tin person person-outlined function overloads.

Arsenic already mentioned earlier, successful C++, and to the opposite to Java, person-sorts are not thought-about 2nd-people residents of the communication, once in contrast to constructed-successful sorts. Truthful, if constructed-successful varieties person operators, person sorts ought to beryllium capable to person them, excessively.

The fact is that, similar the toString(), clone(), equals() strategies are for Java (i.e. quasi-modular-similar), C++ function overloading is truthful overmuch portion of C++ that it turns into arsenic earthy arsenic the first C operators, oregon the earlier talked about Java strategies.

Mixed with template programming, function overloading turns into a fine identified plan form. Successful information, you can not spell precise cold successful STL with out utilizing overloaded operators, and overloading operators for your ain people.

…however it ought to not beryllium abused

Function overloading ought to try to regard the semantics of the function. Bash not subtract successful a + function (arsenic successful “bash not subtract successful a adhd relation”, oregon “instrument crap successful a clone technique”).

Formed overloading tin beryllium precise unsafe due to the fact that they tin pb to ambiguities. Truthful they ought to truly beryllium reserved for fine outlined circumstances. Arsenic for && and ||, bash not always overload them except you truly cognize what you’re doing, arsenic you’ll suffer the the abbreviated circuit valuation that the autochthonal operators && and || bask.

Truthful… Fine… Past wherefore it is not imaginable successful Java?

Due to the fact that James Gosling stated truthful:

I near retired function overloading arsenic a reasonably individual prime due to the fact that I had seen excessively galore group maltreatment it successful C++.

James Gosling. Origin: http://www.gotw.ca/publications/c_family_interview.htm

Delight comparison Gosling’s matter supra with Stroustrup’s beneath:

Galore C++ plan choices person their roots successful my dislike for forcing group to bash issues successful any peculiar manner […] Frequently, I was tempted to outlaw a characteristic I personally disliked, I refrained from doing truthful due to the fact that I did not deliberation I had the correct to unit my views connected others.

Bjarne Stroustrup. Origin: The Plan and Development of C++ (1.three Broad Inheritance)

Would function overloading payment Java?

Any objects would enormously payment from function overloading (factual oregon numerical sorts, similar BigDecimal, analyzable numbers, matrices, containers, iterators, comparators, parsers and many others.).

Successful C++, you tin net from this payment due to the fact that of Stroustrup’s humility. Successful Java, you’re merely screwed due to the fact that of Gosling’s individual prime.

May it beryllium added to Java?

The causes for not including function overloading present successful Java might beryllium a premix of inner government, allergy to the characteristic, mistrust of builders (you cognize, the saboteur ones that look to hang-out Java groups…), compatibility with the former JVMs, clip to compose a accurate specification, and many others..

Truthful don’t clasp your activity ready for this characteristic…

However they bash it successful C#!!!

Yea…

Piece this is cold from being the lone quality betwixt the 2 languages, this 1 ne\’er fails to amuse maine.

Seemingly, the C# of us, with their “all primitive is a struct, and a struct derives from Entity”, received it correct astatine archetypal attempt.

And they bash it successful another languages!!!

Contempt each the FUD towards utilized outlined function overloading, the pursuing languages activity it: Kotlin, Scala, Dart, Python, F#, C#, D, Algol sixty eight, Smalltalk, Groovy, Raku (previously Perl 6), C++, Ruby, Haskell, MATLAB, Eiffel, Lua, Clojure, Fortran ninety, Swift, Ada, Delphi 2005

Truthful galore languages, with truthful galore antithetic (and typically opposing) philosophies, and but they each hold connected that component.

Nutrient for idea…