JavaRush /Java Blog /Random EN /Coffee break #111. Polymorphism and dynamic binding in Ja...

Coffee break #111. Polymorphism and dynamic binding in Java. For loop in Java + forEach loop syntax example

Published in the Random EN group

Polymorphism and dynamic binding in Java

Source: DZone Polymorphism is one of the core concepts of object-oriented programming. Whether you're new to Java programming or a seasoned developer, you should know what polymorphism is and how it works. Most developers claim to be well versed in this topic, but when it comes to other complex features like static and dynamic binding, many of them lose their confidence. Coffee break #111.  Polymorphism and dynamic binding in Java.  For loop in Java + forEach loop syntax example - 1

What is polymorphism in Java?

Polymorphism means having many forms. In programming, this refers to the ability of a signal or message to appear in more than one form.

Real life example

A person can exhibit many characteristics at the same time. For example, a mother can be simultaneously a wife, a daughter, a sister, a company employee, and so on. Therefore, a person may exhibit different characteristics under different conditions. This is known as polymorphism.

The Importance of Polymorphism

Polymorphism is one of the most important features of any object-oriented programming language (for example, Java). With the help of polymorphism, the same task can be performed in different ways.

Types of polymorphism

In Java, polymorphism can be divided into two categories:
  1. Compile-time polymorphism (static linking)
  2. Runtime polymorphism (Runtime, dynamic binding)

Compile-time polymorphism

Compile-time polymorphism is also known as static linking. This type of polymorphism can be achieved through function overloading or operator overloading. But in Java, this is limited to function overloading since Java does not support operator overloading. Function Overloading When there are at least two functions or methods with the same function name, but either the number of parameters they contain is different, or at least one data type of the corresponding parameter is different (or both), then it is called function or method overloading, and these functions are known as overloaded functions. Example 1 So far we have studied what function overloading is. Now let's try to demonstrate software function overloading.
class Main {

    // Method 1
    // Method with 2 integer parameters
    static int Addition(int a, int b)
    {

        // Returns sum of integer numbers
        return a + b;
    }
    // Method 2
    // having the same name but with 2 double parameters
    static double Addition(double a, double b)
    {
        // Returns sum of double numbers
        return a + b;
    }
    public static void main(String args[]) {

        // Calling method by passing
        // input as in arguments
        System.out.println(Addition(12, 14));
        System.out.println(Addition(15.2, 16.1));

    }
}
You can run the above program here . Program explanation:
  • The above program consists of two static functions with the same names: Addition .

  • Here, both functions contain the same number of parameters, but their corresponding parameters are different.

  • Method 1 accepts two integer parameters, while Method 2 accepts two double parameters .

  • From the main function, we first call the Addition(12, 14) function . The parameters passed are integers (12 and 14), so Method 1 will be called here.

  • Then we called the Addition(15.2, 16.1) function . Since the parameters passed are of double data type (15.2 and 16.1), Method 2 will be called this time .

  • This is how function overloading is achieved in Java based on different parameter data types.

Example 2 Consider the program below:
class Main {

    // Method 1
    // Method with 2 integer parameters
    static int Addition(int a, int b)
    {

        // Returns sum of integer numbers
        return a + b;
    }

    // Method 2
    // having the same name but with 3 integer parameters
    static double Addition(double a, double b)
    {

        // Returns sum of integer numbers
        return a + b;
    }
    public static void main(String args[]) {

        // Calling method by passing
        // input as in arguments
        System.out.println(Addition(12, 14));
        System.out.println(Addition(15.2, 16.1));

    }
}
You can run the above program here . Program explanation:
  • The above program consists of two static functions with the same names: Addition .

  • Here, both the functions contain different number of parameters, but the data type of the first two corresponding parameters is the same (integer).

  • Method 1 takes two integer parameters, and Method 2 takes three integer data type parameters.

  • From the main function, we first call the Addition(2, 3) function . Since the passed parameters are integers (2 and 3), they will call Method 1 here .

  • Then we called the Addition(4, 5, 6) function . The parameters passed are double data types (4, 5, 6), so they will call Method 2 this time .

  • This is how functions are overloaded in Java based on a different number of parameters.

Example 3
class Main {

    // Method 1
    // Method with 2 integer parameters
    static int Addition(int a, int b)
    {
        // Return the sum
        return a + b;
    }
    // Method 2
    // having the same name but with 3 parameters
    // 1st parameter is of type double and other parameters
    // are of type integer
    static double Addition(double a, int b,  int c)
    {
        // Return the sum
        return a + b + c;
    }
    public static void main(String args[]) {

        // Calling method by passing
        // input as in arguments
        System.out.println(Addition(2, 4));
        System.out.println(Addition(4.2, 6, 10));

    }
}
You can run the above program here . Program explanation:
  • The above program consists of two static functions with the same names: Addition .

  • Both functions contain a different number of parameters and the data type of the first corresponding element is also different.

  • Method 1 takes two integer parameters, while Method 2 takes three parameters - the first is of type double and the other two are integer data types.

  • From the main function, we first call the Addition(2, 4) function . Since the passed parameters are integers (2 and 4), they will call Method 1 here .

  • Then we called the Addition(4.2, 6, 10) function . The first parameter passed is of integer type and the remaining parameters are of double (4.2, 6, 10) data type, so Method 2 will be called this time .

  • This is how Java achieves function overloading based on different numbers of parameters as well as different data types of the corresponding parameters.

Note. A function cannot be overloaded based solely on the function's return type.

Runtime polymorphism

This option is also known as dynamic linking. In this process, calling a function created for another function is only allowed at runtime. We can achieve dynamic binding in Java using method overriding.

Method overriding

Method overriding in Java occurs when a method in a base class has a definition in a derived class. A base class method or function is called an overridden method.
// Class 1
class Parent {

    // Print method
    void Print()
    {

        // Print statement
        System.out.println("Inside Parent Class");
    }
}

// Class 2
class Child1 extends Parent {

    // Print method
    void Print() { System.out.println("Inside Child1 Class"); }
}

// Class 3
class Child2 extends Parent {

    // Print method
    void Print()
    {
        // Print statement
        System.out.println("Inside Child2 Class");
    }
}

class Main {

    public static void main(String args[]) {

        // Creating an object of class Parent
        Parent parent = new Parent();
        parent.Print();

        // Calling print methods
        parent = new Child1();
        parent.Print();

        parent = new Child2();
        parent.Print();
    }
}
You can run the above program here . Program explanation:
  • The above program consists of three classes: Parent ( class 1 ), Child1 ( class 2 ) and Child2 ( class 3 ). Class 2 and class 3 inherit class 1 .

  • Parent has a method called Print() . Inside this function we print " Inside Parent Class ". Child1 and Child2 also have Print() functions , which basically override the Print() function of the Parent class and print " Inside Child1 Class " and " Inside Child2 Class " respectively to the console.

  • From the main function, we first create an object of the parent class called parent. We then use this object to call the print method of the parent class . Therefore " Inside Parent Class " will be printed on the console.

  • After that, we call the default constructor of the Child1 class and call the Print() function . Note that the Print() method defined in the Child1 class will now be called because we have overridden the Print() method of the parent class . Therefore, " Inside Child1 Class " will be printed on the console.

  • Finally, we call the default constructor of the Child2 class and call the Print() function . Here the Print() method defined in the Child2 class will be called because we have overridden the Print() method of the parent class . Therefore, “ Inside Child2 Class ” will be printed on the console.

  • This is how method overriding is achieved in Java.

Results

In this article, we learned what polymorphism is in Java. We then delved deeper into the topic and discussed two types of polymorphism in Java: compile-time polymorphism and run-time polymorphism. We have demonstrated through programs how static and dynamic binding can be achieved in Java.

For loop in Java + forEach loop syntax example

Source: FreeCodeCamp A Loop in programming is a sequence of instructions that are executed continuously until a certain condition is met. In this article, we will learn about for and forEach loops in Java. Coffee break #111.  Polymorphism and dynamic binding in Java.  For loop in Java + forEach loop syntax example - 2

For Loop Syntax in Java

Here is the syntax for creating a for loop :
for (initialization; condition; increment/decrement) {
   // code to be executed
}
Let's look at some of the keywords in the code:
  • for indicates that we are going to create a loop. It is followed by parentheses, which contain everything we need to make our loop work.

  • initialization defines the initial variable as the starting point of the loop, usually an integer.

  • condition specifies how many times the loop should be executed.

  • increment / decrement increments/decrements the value of the initial variable each time the loop is run. As the value of the variable increases/decreases, it tends to the specified condition.

  • Note that each keyword is separated by a semicolon ( ; ).

Here are some examples:
for(int x = 1; x <=5; x++) {
  System.out.println(x);
}

/*
1
2
3
4
5
*/
In the example above, the starting variable is x with a value of 1. The loop will continue to run as long as the value of x is less than or equal to 5 - this is the condition. x++ increments the value of x after each run. We continued printing the value of x which stops after 5 because the condition was met. Increasing to 6 is not possible because it is greater than and not equal to 5. In the following example, we will use a for loop to print out all the values ​​in an array.
int[] randomNumbers = {2, 5, 4, 7};
for (int i = 0; i < randomNumbers.length; i++) {
  System.out.println(randomNumbers[i]);
}

// 2
// 5
// 4
// 7
This is almost the same as the last example. Here we have used the length of the array as a condition and the initial value of the variable as zero because the ordinal number of the first element of the array is zero.

forEach loop syntax in Java

The forEach loop is used specifically to iterate through the elements of an array. This is what its syntax looks like:
for (dataType variableName : arrayName) {
  // code to be executed
}
You'll notice that the syntax here is shorter than the for loop . And the forEach loop also starts with the for keyword . Instead of initializing a variable with a value, we first specify the data type (it must match the data type of the array). This is followed by the name of our variable and the name of the array , separated by a colon. Here's an example to help you understand the syntax better:
int[] randomNumbers = {2, 5, 4, 7};
for (int x : randomNumbers) {
  System.out.println(x + 1);
}

/*
3
6
5
8
*/
In this example, we have iterated through each element and incremented their initial value by 1. By default, the loop stops once it has iterated through all the elements of the array. This means that we don't need to pass any value to our variable or specify any condition for the loop to end.

Conclusion

In this article, we learned what loops are and the syntax for creating for and forEach loops in Java. We also saw some examples that helped us understand when and how to use them. Happy coding!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION