Rumah  >  Artikel  >  Java  >  Overloading dan Overriding dalam Java

Overloading dan Overriding dalam Java

WBOY
WBOYasal
2024-08-30 15:43:55671semak imbas

Mari kita lihat dahulu apa yang dicadangkan oleh nama itu pada pandangan pertama. "Melebihi muatan" bermaksud: meletakkan sedikit beban tambahan pada fungsi asal sesiapa sahaja, bukan? Sementara itu, "Mengatasi" bermaksud menyediakan kefungsian baharu sebagai tambahan kepada kefungsian asal sesiapa sahaja.  Dalam artikel ini, kita akan melihat Overloading dan Overriding dalam Java secara terperinci. Ya, melaksanakan ini secara pemrograman di Jawa mengikut pendekatan yang sama. Mari kita lihat mereka satu persatu.

Melebihi beban di Jawa

Apabila kelas java mempunyai berbilang kaedah dengan nama yang sama tetapi dengan hujah yang berbeza, kami memanggilnya Method Overloading. Dengan mengekalkan nama yang sama, kami hanya meningkatkan kebolehbacaan kod program. Sebagai contoh, katakan kita perlu melakukan beberapa operasi tambah pada beberapa nombor tertentu. Katakan nama kaedah kami ialah "tambahan()".  Di sini, penambahan boleh dilakukan antara dua, tiga, atau lebih. Oleh itu, bergantung pada bilangan nombor yang akan terlibat dalam operasi tambahan, kita boleh menukar argumen (atau parameter) fungsi. Tetapi, sebaliknya, jika anda menulis kaedah yang berbeza untuk bilangan hujah yang berbeza, sukar untuk dikenali kerana nama itu berbeza.  Oleh itu, dengan lebihan beban, kami mencapai kebolehbacaan kod kami yang lebih baik. Jadi sekarang persoalannya, bagaimana kita akan mencapai lebihan beban?

Mulakan Kursus Pembangunan Perisian Percuma Anda

Pembangunan web, bahasa pengaturcaraan, ujian perisian & lain-lain

Mari kita lihat satu persatu dengan kod contoh.

#1 – Dengan mengubah suai bilangan parameter

Jadi di sini, kami akan melakukan operasi tambahan pada beberapa nombor. Untuk ini, mari kita buat kelas yang dipanggil "Operasi Tambahan". Di dalam kelas itu, mari kita mempunyai dua kaedah bernama "tambahan()". Dalam salah satu kaedah tersebut, kami akan menambah dua nombor. Dalam yang lain, kami akan menambah tiga nombor. Kami akan mencapai ini dengan menukar bilangan parameter dalam kaedah tersebut, tetapi kami akan mengekalkan nama yang sama. Dengan cara ini, kami membebankan kaedah “tambahan()” di sini.

Kod:

public class AdditionOperation {
static int addition(int num1,int num2){return num1+num2;} //function declarationand definition for addition of two numbers
static int addition(int num1,int num2,int num3){return num1+num2+num3;} //function declarationand definition for addition of three numbers
public static void main(String args[]) {
system.out.printin(addition(35,36)); //method overloading
system.out.printin(addition(35,36,37)); //method overloading, we are calling same methods but for different number of arguments.
}
}

Output:

Overloading dan Overriding dalam Java

#2 – Dengan mengubah suai jenis data

Di sini, kami akan melakukan operasi tambah pada jenis yang berbeza, contohnya, antara jenis integer dan dua jenis. Untuk ini, mari kita buat kelas yang dipanggil "Operasi Tambahan". Di dalam kelas itu, mari kita mempunyai dua kaedah bernama "tambahan()". Dalam salah satu kaedah tersebut, kami akan menambah dua integer. Dalam yang lain, kami akan menambah dua beregu. Kami akan mencapai ini dengan menukar jenis parameter dalam kaedah tersebut, tetapi kami akan mengekalkan nama yang sama. Dengan cara ini, kami membebankan kaedah “tambahan()” di sini.

Kod:

public class additionOperation {
static int addition(int num1,int num2){return num1+num2;} //function declarationand definition for addition of two numbers
static double addition(double num1,num2){return num1+num2;} //function declarationand definition for addition of three numbers
public static void main(String args[]) {
system.out.printin(addition(35,36)); //method overloading
system.out.printin(addition(35.5,36.6)); //method overloading, we are calling same methods but for different type of arguments.
}
}

Output:

Overloading dan Overriding dalam Java

Mata yang Perlu Diperhatikan kerana Lebih Muatan

  • Overloading in java is basically a “compile-time polym Method Overloading in C#orphism”. Compile-time polymorphism in java is also called “Static method Dispatch” or “Early binding”. So what do I mean by that jargon?
  • As the name suggests, polymorphism is basically an ability to take many forms (poly: many, morph: form). The linking or binding of the overridden function and the object occurs at compile time. Compile-time polymorphism earns its name because function binding to an object occurs early, specifically during compile time, rather than at runtime. It is also called “Early binding” to emphasize this early binding process.
  • Static dispatch is a type of polymorphism or method dispatch that tells how java will select which functionality of the method will be used in compile time. (I mean, whether it will add two or three numbers in our coding example).  The name is also known as the Static method Dispatch.

Overriding in Java

  • When a java subclass or child class has a method that is of the same name and contains the same parameters or arguments and a similar return type as a method that is present in its superclass or parent class, then we can call the method of the child class as an overridden method of the method of its parent class.
  • For example, suppose we need to perform some display operation according to its class type. If I call the method of a parent class, it will display a message defined in a parent class. But, calling the child class method will override the display message of its parent class and display the message defined within the child class method. Hence depending on which display we need to show, we can call the related class (parent or child). We are not changing the method name, argument, and return type here. We are just changing the functionality of the method in the child class. But, instead of this, if we do not do overriding, i. e. we don’t give the specific implementation of the child method, then while calling the method, it will display the same message as present in a parent class.
  • When writing code, use the @Override annotation before overriding a method. This annotation informs the compiler that the method must override a declaration in a superclass. Although using this is not mandatory, it helps prevent errors. If a method annotated with @Override fails to override a method, the compiler generates an error.

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

Code:

//Parent or Super class
class Parent {
public void display() {
system.out.printin("Hello, I am from parent class");
}
}
//Child or sub class
class Sub extends Parent {
//Below method overrides the Parent display() method
// @override
public void display() {
system.out.printin("Hello, I am from child class");
}
}
//Driver class
public class Overriding {
public static void main?(String args[])
{
Parent superObject = new Parent ();
superObject.display(); // Super class method is called
Parent subObject = new Sub();
subObject.display(); //Child class method is called by a parent type reference: this is functionality of method overriding
Sub subObject2 = new Sub(); //Child class method is called by a child type reference
subObject2.display();
}
}

Output:

Overloading dan Overriding dalam Java

Limitations in method Overriding:

  1. The child class cannot override the private methods of the parent class.
  2. You cannot override final methods.
  3. One cannot override static methods.

Points to be Noted for Overriding

  • Overriding in Java represents “run-time polymorphism,” also known as “dynamic method dispatch” or “late binding.” These terms refer to the ability of the Java runtime system to determine the appropriate method implementation to execute based on the actual type of the object at runtime.
  • As the name suggests, polymorphism is basically an ability to take many forms (poly: many, morph: form). So, a call to an overridden function with the object is done during the run time. Hence called run time polymorphism.
  • Late binding, or “dynamic binding,” occurs after compilation during runtime, as it binds functions to objects.
  • Dynamic dispatch is a type of polymorphism or method dispatch that tells how java will select which method functionality will be used in run time. The name is also known as Dynamic method Dispatch.

Conclusion

This concludes our learning of the topic “Overloading and Overriding in Java”. Write the codes mentioned above in the java compiler and check the output. Learning codes will be incomplete if you do not do hands-on by yourself, enhancing your coding skills.  Happy coding!!

Atas ialah kandungan terperinci Overloading dan Overriding dalam Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Polimorfisme Runtime dalam JavaArtikel seterusnya:Polimorfisme Runtime dalam Java