![]() ![]() Java compiler differentiates multiple methods having the same name by their signatures. In this way, compile-time polymorphism allows us to perform various operations by using multiple methods with the same name. Thus, Java compiler matches the values passed to a method during compilation, binds method call with appropriate method definition, and calls the appropriate method. Similarly, when we call the second sum() method by passing three int type argument values, Java compiler binds the definition of sum(int x, int y, int z) with sum(10, 20, 30) method during compilation, and calls a method of the sum of three numbers. Hence, the sum of two numbers is displayed by invoking sum() method on the console. When we will call the first sum() method using reference variable “obj” by passing two int type argument values, Java compiler binds the definition of sum(int x, int y) method with sum(20, 10) method during compilation and calls the appropriate method. The first sum() method accepts two parameters whereas, the second sum() method accepts three parameters. ("Sum of three numbers: " +s) Īs you can observe in the preceding example program, the sum() method is overloaded two times because both methods’ signatures vary in the number of parameters. Program source code 1: package staticPolymorphism Both of these methods will have different signatures. In this class, we will create two methods having the same name sum. Let’s take an example program where we will implement static polymorphism. In this example program, we will create a class StaticPoly. Java Compile-time Polymorphism Example Program It is one of the ways that Java implements polymorphism.Īnother example of static polymorphism is constructor overloading and method hiding. Method overloading is a mechanism in which a class has multiple methods having the same name but different signatures. Compile-time polymorphism can be achieved/implemented by method overloading in java. Since binding is performed at compile-time, it is also known as early binding. ![]() Therefore, this type of polymorphism is also called compile-time polymorphism in Java. Hence, Java compiler binds method calls with method definition/body during compilation. In static polymorphism, the behavior of a method is decided at compile-time. Static Polymorphism in JavaĪ polymorphism that exhibited during compilation is called static polymorphism in java. Polymorphism can be either static or dynamic depending on how the method is called in a class. Basically, there are two types of polymorphism in java. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |