- Java 9 Programming By Example
- Peter Verhas
- 374字
- 2021-07-02 23:37:35
Argument passing
In Java, arguments are passed by value. When the method modifies an argument variable, then only the copy of the original value is modified. Any primitive value is copied during the method call. When an object is passed as an argument, then the copy of the reference to the object is passed.
That way, the object is available to be modified for the method. In the case of classes that have their primitive counterpart, and also in the case of String and some other class types, the objects simply do not provide methods or fields to modify the state. This is important for the integrity of the language, and to not get into trouble when objects and primitive values automatically get converted.
In other cases, when the object is modifiable, the method can effectively work on the very object it was passed to. This is also the way the sort method in our example works on the array. The same array, which is also an object itself, is modified.
This argument passing is much simpler than it is in other languages. Other languages let the developer mix the pass by reference and the pass by value argument passing. In Java, when you use a variable by itself as an expression to pass a parameter to a method, you can be sure that the variable itself is never modified. The object it refers to, however, in case it is mutable, may be modified.
An object is mutable if it can be modified, altering the value of some of its field directly or via some method call. When a class is designed in a way that there is no normal way to modify the state of the object after the creation of the object, the object is immutable. The classes Byte, Short, Integer, Long, Float, Double, Boolean, Character, as well as String, are designed in the JDK so that the objects are immutable.
It is possible to overcome the limitation of immutability implementation of certain classes using reflection, but doing that is hacking and not professional coding. Doing that can be done for one single purpose—getting a better knowledge and understanding of the inner workings of some Java classes, but nothing else.
- Python程序設計(第3版)
- C#程序設計(慕課版)
- Python從入門到精通(精粹版)
- Functional Programming in JavaScript
- Learning Python Design Patterns(Second Edition)
- Linux操作系統基礎案例教程
- 全棧自動化測試實戰:基于TestNG、HttpClient、Selenium和Appium
- 零基礎入門學習Python(第2版)
- Lighttpd源碼分析
- SSM開發實戰教程(Spring+Spring MVC+MyBatis)
- 計算機應用基礎案例教程
- 匯編語言編程基礎:基于LoongArch
- Android開發三劍客:UML、模式與測試
- 從零開始:UI圖標設計與制作(第3版)
- 工業機器人離線編程