Metode overloading di JVM

Selamat datang di blog Java Challengers baru ! Blog ini didedikasikan untuk konsep menantang dalam pemrograman Java. Kuasai mereka dan Anda akan segera menjadi programmer Java yang sangat terampil.

Teknik-teknik di blog ini membutuhkan usaha untuk dikuasai, tetapi teknik tersebut akan membuat perbedaan besar dalam pengalaman harian Anda sebagai pengembang Java. Menghindari bug lebih mudah jika Anda tahu cara menerapkan teknik pemrograman inti Java dengan benar, dan melacak bug jauh lebih mudah saat Anda tahu persis apa yang terjadi pada kode Java Anda.

Apakah Anda siap untuk mulai menguasai konsep inti dalam pemrograman Java? Maka mari kita mulai dengan Java Challenger pertama kami!  

Terminologi: Metode overloading

Karena istilah overloading , developer cenderung menganggap teknik ini akan membebani sistem, tetapi itu tidak benar. Dalam pemrograman, metode overloading berarti menggunakan nama metode yang sama dengan parameter yang berbeda. 

Apa metode overloading?

Metode overloading adalah teknik pemrograman yang memungkinkan pengembang menggunakan nama metode yang sama beberapa kali di kelas yang sama, tetapi dengan parameter yang berbeda. Dalam kasus ini, kami mengatakan bahwa metode tersebut kelebihan beban. Kode 1 menunjukkan satu metode yang parameternya berbeda dalam jumlah, jenis, dan urutan.

Daftar 1. Tiga jenis metode overloading

 Number of parameters: public class Calculator { void calculate(int number1, int number2) { } void calculate(int number1, int number2, int number3) { } } Type of parameters: public class Calculator { void calculate(int number1, int number2) { } void calculate(double number1, double number2) { } } Order of parameters: public class Calculator { void calculate(double number1, int number2) { } void calculate(int number1, double number2) { } } 

Metode overloading dan tipe primitif

Dalam Daftar 1, Anda melihat tipe primitif intdan double. Kami akan bekerja lebih banyak dengan ini dan tipe lainnya, jadi luangkan waktu sebentar untuk meninjau tipe primitif di Java.

Tabel 1. Tipe primitif di Jawa

Tipe Jarak Default Ukuran Contoh literal
 boolean  benar atau salah  Salah  1 bit  benar salah
 byte  -128 .. 127  0  8 bit  1, -90, 128
 char  Karakter unicode atau 0 hingga 65.536  \ u0000  16 bit  'a', '\ u0031', '\ 201', '\ n', 4
 short  -32.768 .. 32.767  0  16 bit  1, 3, 720, 22.000
 int  -2.147.483.648 .. 2.147.483.647  0  32 bit  -2, -1, 0, 1, 9
 long  -9.223.372.036.854.775.808 hingga 9.223.372.036.854.775.807  0  64 bit  -4000L, -900L, 10L, 700L
 float  3,40282347 x 1038, 1,40239846 x 10-45  0.0  32 bit  1.67e200f, -1.57e-207f, .9f, 10.4F
 double

 1,7976931348623157 x 10308, 4,9406564584124654 x 10-324

 0.0  64 bit  1.e700d, -123457e, 37e1d

Mengapa saya harus menggunakan metode overloading?

Kelebihan beban membuat kode Anda lebih bersih dan lebih mudah dibaca, dan ini juga dapat membantu Anda menghindari bug dalam program Anda.

Berbeda dengan Listing 1, bayangkan program di mana Anda memiliki beberapa calculate()metode dengan nama seperti calculate1 calculate2,, calculate3. . . tidak bagus kan? Membebani calculate()metode memungkinkan Anda menggunakan nama metode yang sama sambil hanya mengubah apa yang perlu diubah: parameter. Menemukan metode yang kelebihan beban juga sangat mudah karena mereka dikelompokkan bersama dalam kode Anda.

Apa kelebihan beban tidak

Ketahuilah bahwa mengubah nama variabel tidak membebani secara berlebihan. Kode berikut tidak dapat dikompilasi:

 public class Calculator { void calculate(int firstNumber, int secondNumber){} void calculate(int secondNumber, int thirdNumber){} } 

Anda juga tidak bisa membebani metode dengan mengubah tipe kembalian di tanda tangan metode. Kode berikut juga tidak dapat dikompilasi:

 public class Calculator { double calculate(int number1, int number2){return 0.0;} long calculate(int number1, int number2){return 0;} } 

Konstruktor kelebihan beban

Anda dapat membebani konstruktor dengan cara yang sama seperti Anda menggunakan metode:

 public class Calculator { private int number1; private int number2; public Calculator(int number1) {this.number1 = number1;} public Calculator(int number1, int number2) { this.number1 = number1; this.number2 = number2; } } 

Ambil tantangan metode overloading!

Apakah Anda siap untuk Java Challenger pertama Anda? Mari kita cari tahu!

Mulailah dengan meninjau kode berikut dengan cermat.

Daftar 2. Tantangan overloading metode lanjutan

 public class AdvancedOverloadingChallenge3 { static String x = ""; public static void main(String... doYourBest) { executeAction(1); executeAction(1.0); executeAction(Double.valueOf("5")); executeAction(1L); System.out.println(x); } static void executeAction(int ... var) {x += "a"; } static void executeAction(Integer var) {x += "b"; } static void executeAction(Object var) {x += "c"; } static void executeAction(short var) {x += "d"; } static void executeAction(float var) {x += "e"; } static void executeAction(double var) {x += "f"; } } 

Oke, Anda sudah meninjau kodenya. Apa hasilnya?

  1. befe
  2. bfce
  3. efce
  4. aecf

Cek jawaban Anda di sini.

Apa yang baru saja terjadi? Bagaimana JVM mengompilasi metode yang kelebihan beban

Untuk memahami apa yang terjadi pada Listing 2, Anda perlu mengetahui beberapa hal tentang bagaimana JVM mengkompilasi metode yang kelebihan beban.

Pertama-tama, JVM secara cerdas malas : JVM akan selalu mengerahkan upaya seminimal mungkin untuk mengeksekusi metode. Jadi, ketika Anda memikirkan tentang bagaimana JVM menangani kelebihan beban, perhatikan tiga teknik kompiler penting:

  1. Pelebaran
  2. Tinju (autoboxing dan unboxing)
  3. Varargs

Jika Anda belum pernah menemukan ketiga teknik ini, beberapa contoh akan membantu memperjelasnya. Perhatikan bahwa JVM mengeksekusinya dalam urutan yang diberikan .

Berikut contoh pelebaran :

 int primitiveIntNumber = 5; double primitiveDoubleNumber = primitiveIntNumber ; 

Ini adalah urutan tipe primitif saat dilebarkan:

Rafael del Nero

Berikut ini contoh autoboxing :

 int primitiveIntNumber = 7; Integer wrapperIntegerNumber = primitiveIntNumber; 

Perhatikan apa yang terjadi di balik layar ketika kode ini dikompilasi:

 Integer wrapperIntegerNumber = Integer.valueOf(primitiveIntNumber); 

Dan berikut ini contoh  unboxing :

 Integer wrapperIntegerNumber = 7; int primitiveIntNumber= wrapperIntegerNumber; 

Inilah yang terjadi di balik layar ketika kode ini dikompilasi:

 int primitiveIntNumber = wrapperIntegerNumber.intValue(); 

Dan ini adalah contoh vararg ; perhatikan bahwa varargsselalu yang terakhir dieksekusi:

 execute(int… numbers){} 

Apa itu varargs?

Used for variable arguments, varargs is basically an array of values specified by three dots (…) We can pass however many int numbers we want to this method.

For example:

execute(1,3,4,6,7,8,8,6,4,6,88...); // We could continue… 

Varargs is very handy because the values can be passed directly to the method. If we were using arrays, we would have to instantiate the array with the values.

Widening: A practical example

When we pass the number 1 directly to the executeAction method, the JVM automatically treats it as an int. That’s why the number doesn't go to the executeAction(short var) method.

Similarly, if we pass the number 1.0, the JVM automatically recognizes that number as a double.

Of course, the number 1.0 could also be a float, but the type is pre-defined. That’s why the executeAction(double var) method is invoked in Listing 2.

When we use the Double wrapper type, there are two possibilities: either the wrapper number could be unboxed to a primitive type, or it could be widened into an Object. (Remember that every class in Java extends the Object class.) In that case, the JVM chooses to wided the Double type to an Object because it takes less effort than unboxing would,  as I explained before.

The last number we pass is 1L, and because we've specified the variable type this time, it is long.

Video challenge! Debugging method overloading

Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video you can follow along while I debug and explain the method overloading challenge:

Common mistakes with overloading

By now you’ve probably figured out that things can get tricky with method overloading, so let’s consider a few of the challenges you will likely encounter.

Autoboxing with wrappers

Java is a strongly typed programming language, and when we use autoboxing with wrappers there are some things we have to keep in mind. For one thing, the following code won't compile:

 int primitiveIntNumber = 7; Double wrapperNumber = primitiveIntNumber; 

Autoboxing will only work with the double type because what happens when you compile this code is the same as the following:

 Double number = Double.valueOf(primitiveIntNumber); 

The above code will compile. The first int type will be widened to double and then it will be boxed to Double. But when autoboxing, there is no type widening and the constructor from Double.valueOf will receive a double, not an int. In this case, autoboxing would only work if we applied a cast, like so:

 Double wrapperNumber = (double) primitiveIntNumber; 

Remember that Integer cannot be Long and Float cannot be Double. There is no inheritance. Each of these types--Integer, Long, Float, and Double--is a Number and an Object.

When in doubt, just remember that wrapper numbers can be widened to Number or Object. (There is a lot more to explore about wrappers but I will leave it for another post.)

Hard-coded number types in the JVM

When we don’t specify a type to a number, the JVM will do it for us. If we use the number 1 directly in the code, the JVM will create it as an int. If you try to pass 1 directly to a method that is receiving a short, it won’t compile.

For example:

 class Calculator { public static void main(String… args) { // This method invocation will not compile // Yes, 1 could be char, short, byte but the JVM creates it as an int calculate(1); } void calculate(short number) {} } 

The same rule will be applied when using the number 1.0; although it could be a float, the JVM will treat this number as a double:

 class Calculator { public static void main(String… args) { // This method invocation will not compile // Yes, 1 could be float but the JVM creates it as double calculate(1.0); } void calculate(float number) {} } 

Another common mistake is to think that the Double or any other wrapper type would be better suited to the method that is receiving a double. In fact, it takes less effort for the JVM to widen the Double wrapper to an Object instead of unboxing it to a double primitive type.

To sum up, when used directly in Java code, 1 will be int and 1.0 will be double. Widening is the laziest path to execution, boxing or unboxing comes next, and the last operation will always be varargs.

As a curious fact, did you know that the char type accepts numbers?

 char anyChar = 127; // Yes, this is strange but it compiles 

What to remember about overloading

Overloading is a very powerful technique for scenarios where you need the same method name with different parameters. It’s a useful technique because having the right name in your code makes a big difference for readability. Rather than duplicate the method and add clutter to your code, you may simply overload it. Doing this keeps your code clean and easy to read, and it reduces the risk that duplicate methods will break some part of the system.

What to keep in mind: When overloading a method the JVM will make the least effort possible; this is the order of the laziest path to execution:

  • First is widening
  • Second is boxing
  • Third is Varargs

What to watch out for: Tricky situations will arise from declaring a number directly: 1 will be int and 1.0 will be double.

Also remember that you can declare these types explicitly using the syntax of 1F or 1f for a float or 1D or 1d for a double.

That concludes our first Java Challenger, introducing the JVM’s role in method overloading. It is important to realize that the JVM is inherently lazy, and will always follow the laziest path to execution.

 

Answer key

The answer to the Java Challenger in Listing 2 is: Option 3. efce.

More about method overloading in Java

  • Java 101: Classes and objects in Java: A true beginner’s introduction to classes and objects, including short sections on methods and method overloading.
  • Java 101: Elementary Java language features: Learn more about why it matters that Java is a strongly typed language and get a full introduction to primitive types in Java.
  • Terlalu banyak parameter dalam metode Java, Bagian 4: Menjelajahi batasan dan kerugian metode overloading, dan bagaimana cara memperbaikinya dengan mengintegrasikan objek parameter dan tipe khusus.

Cerita ini, "Metode overloading di JVM" pada awalnya diterbitkan oleh JavaWorld.