Showing posts with label Polymorphism. Show all posts
Showing posts with label Polymorphism. Show all posts

Friday, January 21, 2022

Compile Time Polymorphism in Java

Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Guide, Oracle Java Learning, Core Java, Java Skills, Java Jobs

Polymorphism in Java refers to an object’s capacity to take several forms. Polymorphism allows us to perform the same action in multiple ways in Java.

Polymorphism is divided into two types:

1. Compile-time polymorphism

2. Run time polymorphism

Note: Run time polymorphism is implemented through Method overriding. Whereas, Compile Time polymorphism is implemented through Method overloading and Operator overloading

In this article, we will see Compile time polymorphism.

Compile-time Polymorphism

Compile-time polymorphism is also known as static polymorphism or early binding. Compile-time polymorphism is a polymorphism that is resolved during the compilation process. Overloading of methods is called through the reference variable of a class. Compile-time polymorphism is achieved by method overloading and operator overloading.

1. Method overloading

We can have one or more methods with the same name that are solely distinguishable by argument numbers, type, or order.

Method Overloading occurs when a class has many methods with the same name but different parameters. Two or more methods may have the same name if they have other numbers of parameters, different data types, or different numbers of parameters and different data types. 

Example: 

void ojc() { ... }

void ojc(int num1 ) { ... }

void ojc(float num1) { ... }

void ojc(int num1 , float num2 ) { ... } 

(a). Method overloading by changing the number of parameters 

In this type, Method overloading is done by overloading methods in the function call with a varied number of parameters

Example:

show( char a )

show( char a ,char b )

 In the given example, the first show method has one parameter, and the second show method has two methods. When a function is called, the compiler looks at the number of parameters and decides how to resolve the method call.

// Java program to demonstrate the working of method

// overloading by changing the number of parameters

public class MethodOverloading {

// 1 parameter

void show(int num1)

{

System.out.println("number 1 : " + num1);

}

// 2 parameter

void show(int num1, int num2)

{

System.out.println("number 1 : " + num1

+ " number 2 : " + num2);

}

public static void main(String[] args)

{

MethodOverloading obj = new MethodOverloading();

// 1st show function

obj.show(3);

// 2nd show function

obj.show(4, 5);

}

}

Output

number 1 : 3
number 1 : 4  number 2 : 5

In the above example, we implement method overloading by changing several parameters. We have created two methods, show(int num1 ) and show(int num1, int num2 ). In the show(int num1) method display, one number and the void show(int num1, int num2 ) display two numbers

(b). Method overloading by changing Datatype of parameter

In this type, Method overloading is done by overloading methods in the function call with different types of parameters

Example:

show( float a float b)
show( int a, int b ) 

In the above example, the first show method has two float parameters, and the second show method has two int parameters. When a function is called, the compiler looks at the data type of input parameters and decides how to resolve the method call.

Program:

// Java program to demonstrate the working of method
// overloading by changing the Datatype of parameter

public class MethodOverloading {

// arguments of this function are of integer type
static void show(int a, int b)
{
System.out.println("This is integer function ");
}

// argument of this function are of float type
static void show(double a, double b)
{
System.out.println("This is double function ");
}

public static void main(String[] args)
{
// 1st show function
show(1, 2);
// 2nd show function
show(1.2, 2.4);
}
}

Output

This is integer function 
This is double function 

In the above example, we changed the data type of the parameters of both functions. In the first show() function datatype of the parameter is int. After giving integer type input, the output will be ‘ This is integer function.’ In the second show() function datatype of a parameter is double. After giving double type input, the output would be ‘This is double function.’ 

(c). By changing the sequence of parameters 

In this type, overloading is dependent on the sequence of the parameters 

Example:

show( int a, float b ) 
show( float a, int b )

Here in this example, The parameters int and float are used in the first declaration. The parameters are int and float in the second declaration, but their order in the parameter list is different.

// Java program to demonstrate the working of method
// overloading by changing the sequence of parameters

public class MethodOverloading {

// arguments of this function are of int and char type
static void show(int a, char ch)
{
System.out.println("integer : " + a
+ " and character : " + ch);
}

// argument of this function are of char and int type
static void show(char ch, int a)
{
System.out.println("character : " + ch
+ " and integer : " + a);
}

public static void main(String[] args)
{
// 1st show function
show(6, 'O');

// 2nd show function
show('O', 7);
}
}

Output

integer : 6 and character : O
character : O and integer : 7

In the above example, in the first show, function parameters are int and char, and in the second shoe, function parameters are char, and int. changed the sequence of data type. 

Invalid cases of method overloading

Method overloading does not allow changing the return type of method( function ); it occurs ambiguity.

Examples

int sum(int, int);
String sum(int, int);

Because the arguments are matching, the code above will not compile. Both methods have the same amount of data types and the same sequence of data types in the parameters.

2. Operator Overloading 

An operator is said to be overloaded if it can be used to perform more than one function. Operator overloading is an overloading method in which an existing operator is given a new meaning. In Java, the + operator is overloaded. Java, on the other hand, does not allow for user-defined operator overloading. To add integers, the + operator can be employed as an arithmetic addition operator. It can also be used to join strings together.

// Java program to demonstrate the
// working of operator overloading

public class OJC {

// function for adding two integers
void add(int a, int b)
{
int sum = a + b;
System.out.println(" Addition of two integer :"
+ sum);
}

// function for concatenating two strings
void add(String s1, String s2)
{
String con_str = s1 + s2;
System.out.println("Concatenated strings :"
+ con_str);
}

public static void main(String args[])
{
OJC obj = new OJC();
// addition of two numbers
obj.add(10, 10);
// concatenation of two string
obj.add("Operator ", " overloading ");
}
}

Output

Addition of two integer :20
Concatenated strings :Operator  overloading 

In the above example, The ‘+’ operator has been overloaded. When we send two numbers to the overloaded method, we get a sum of two integers, and when we pass two Strings, we get the concatenated text.

Advantages of Compile-time Polymorphism:

1. It improves code clarity and allows for the use of a single name for similar procedures.
2. It has a faster execution time since it is discovered early in the compilation process.

The only disadvantage of compile-time polymorphism is that it doesn’t include inheritance.

Source: geeksforgeeks.org

Friday, July 30, 2021

Interfaces and Polymorphism in Java

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs

Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts.

Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name.

Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading.

Types of polymorphism in Java:

1. Run time polymorphism

2. Compile-time polymorphism

Type 1: Run time polymorphism

This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing I/O classes

import java.io.*;

// Class 1 (Parent class)

class GFG1 {

//name method

void name() {

System.out.println("This is the GFG1 class");

}

}

// Class 2 (Chile class)

// Main class extending parent class

public class GFG extends GFG1 {

// Method 1

void name() {

// Print statement

System.out.println("This is the GFG class");

}

// Method 2

// Main drive method

public static void main(String[] args) {

// Now creating 2 objects with different references and

// calling the Method 1 over the objects

// Case 1: GFG1 reference and GFG1 is the object

GFG1 ob = new GFG1();

ob.name();

// Case 2: GFG1 reference and GFG is the object

GFG1 ob1 = new GFG();

ob1.name();

}

}

Output

This is the GFG1 class
This is the GFG class

Output explanation: 

In the above example, the same function i.e name is called two times, but in both cases, the output is different. The signatures of these methods are also the same. That’s why compilers cannot be able to identify which should be executed. This is determined only after the object creation and reference of the class, which is performed during run time (Memory management ). That’s why this is run-time polymorphism.

Type 2: Compile-time polymorphism

Method overloading is an example of the compile-time polymorphism method. Overloading means a function having the same name but a different signature. This is compile-time polymorphism because this type of polymorphism is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Helper class
class First {

// Method of this class
// Without any parameter
void check()
{

// Print statement if this method is called
System.out.println("This is the class First");
}
}

// Class 2
// Main class
class Second extends First {

// Method overloading
void check(String name)
{
// Printing the name of the class method having the
// parameter
System.out.println("This is the class " + name);
}

// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Second ob = new Second();
// Calling method over class 2 object
ob.check("Second");

// Creating object of class 1
First ob1 = new First();
ob.check();

// Upcasting
First ob2 = new Second();
ob.check();
}
}

Output

This is the class Second
This is the class First
This is the class First

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs
Interfaces are very similar to classes. They have variables and methods but the interfaces allow only abstract methods(that don’t contain the body of the methods), but what is the difference between the classes and the interfaces? The first advantage is to allow interfaces to implement the multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are allowed in Java.

Real-life Example

The real-world example of interfaces is that we have multiple classes for different levels of employees working in a particular company and the necessary property of the class is the salary of the employees and this. We must be implemented in every class and. Also, it is different for every employee here. The concept of the interface is used. We simply create an interface containing an abstract salary method and implement it in all the classes and we can easily define different salaries of the employees.

Example

// Java Program to Demonstarte Concept of interfaces

// Interfacce
interface salary {
void insertsalary(int salary);
}

// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

public class GFG {

public static void main(String[] args)
{
SDE1 ob = new SDE1();
// Insert different salaries
ob.insertsalary(100000);
ob.printSalary();
SDE2 ob1 = new SDE2();

ob1.insertsalary(200000);
ob1.printSalary();
}
}

Output

100000
200000

Source: geeksforgeeks.org

Friday, October 2, 2020

Difference between Inheritance and Polymorphism in Java and Object Oriented Programming

Both Inheritance and Polymorphism are key OOP concepts and similar to Abstraction and Encapsulation, they are also closely related to each other. Because of their similarities, many OOP programmers, especially beginners get confused between Inheritance and Polymorphism. Even though they are closely related and you need Inheritance to support runtime Polymorphism they are a totally different concept. Inheritance refers to the ability for classes or objects to inherit properties of other classes or interfaces. It means you can write code for common functionalities and reuse it at different places by just using Inheritance and not re-writing those codes again and again. For example, you can write code to

Inheritance vs Polymorphism in Java and Object-Oriented Programming

Let's revisit some key differences between Inheritance and Polymorphism in object-oriented programming

1) Class vs Object

Inheritance is used to define a class or interface hierarchy. You extract common functionality on superclass and allow derived classes to get more specific by adding specific functionality. On the other hand, Polymorphism allows you to do the same operation differently depending upon which context and which object is doing the operation.

2)  Code Reuse

One of the key advantages of Inheritance is code reuse. You don't need to write the same code again and again if it is needed by multiple classes. You can extract the common functionality on the base class and let other classes simply use inheritance to get that functionality. In another word, it reduces the amount of duplicate code and promotes DRY practice.

For example, if you are designing a class hierarchy for Finance and Insurance industry, you can create a base class called Insurance, which should have basic properties like covered, the sum assured, premium, etc.

Now, if your application needs to support automobile insurance like the CarInsurance, it just needs to extend the Insurance base class to add specific details required by car insurance companies like the registration number of the car, brand, etc.

Similarly, Health Insurance applications can reuse the same base class for calculating premiums, keeping a record of sum assured, and other basic details. They can further enrich the derived class by adding more specific details required by health insurance companies like pre-existing diseases, co-payment details, etc.

Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Material, Java Prep, Java Certification

Polymorphism can also come handy here to write code for calculating premiums. Assuming, the premium is calculated differently for different types of insurance then you can override the calculatePremium() method in derived or subclasses to represent different types of premium calculation.

The benefit of using Polymorphism here is that all the common functionality like report generations, sending premium receipts, or premium reminders can still use the same the calculatePreimum() method for performing their duty. They don't need to worry about the fact that different types of insurance are calculating premium using different formulas.

3)  Flexibility

If Inheritance provides "code re-usability" then Polymorphism provides the "flexibility" to your code. As I mentioned in my previous example, you can add a new kind of Insurance without re-writing code to generate receipts, premium reminders, and other kinds of reports.
By using Polymorphism, you can encapsulate the code which is different inside the same method declared by the superclass. The Clean Code by Uncle Bob has a good write up and example on this.

Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Material, Java Prep, Java Certification

4)  Right Usage

One of the best practices in the OOP world is using Inheritance for defining type hierarchies using the interface. This is also advised in Effective Java 2nd Edition by Joshua Bloch. By defining types, you create a path for Polymorphism.

5) extends vs implements

Inheritance in Java is implemented using "extends" and "implements" keyword. A class can extend another class or implement one or more interfaces. When it does that, the parent-child relationship is established between two classes or interfaces.

For example, in the following code, the MyClass is now a child or both Canvas and Runnable:

public class MyClass extends Canvas implements Runnable{

@Overide
public void paint(Graphics g){
   ... some code
  }

@Override
public void run(){
  ... some code
  }

}

This means you a reference variable of Runnable or Canvas can point to an object of MyClass and if you call paint() or run() method then these methods will be called instead of paint() method defined in Canvas and run() method defined in Runnable. This is the power of Polymorphism which comes from Inheritance.

Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Material, Java Prep, Java Certification

Source: javarevisited.blogspot.com

Monday, July 6, 2020

Java - Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Java - Polymorphism, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learn

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Example

Let us look at an example.

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −

◉ A Deer IS-A Animal
◉ A Deer IS-A Vegetarian
◉ A Deer IS-A Deer
◉ A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal −

Example

Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d, a, v, o refer to the same Deer object in the heap.

Virtual Methods


In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

Example

/* File name : Employee.java */
public class Employee {
   private String name;
   private String address;
   private int number;

   public Employee(String name, String address, int number) {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }

   public void mailCheck() {
      System.out.println("Mailing a check to " + this.name + " " + this.address);
   }

   public String toString() {
      return name + " " + address + " " + number;
   }

   public String getName() {
      return name;
   }

   public String getAddress() {
      return address;
   }

   public void setAddress(String newAddress) {
      address = newAddress;
   }

   public int getNumber() {
      return number;
   }
}

Now suppose we extend Employee class as follows −

/* File name : Salary.java */
public class Salary extends Employee {
   private double salary; // Annual salary
 
   public Salary(String name, String address, int number, double salary) {
      super(name, address, number);
      setSalary(salary);
   }
 
   public void mailCheck() {
      System.out.println("Within mailCheck of Salary class ");
      System.out.println("Mailing check to " + getName()
      + " with salary " + salary);
   }
 
   public double getSalary() {
      return salary;
   }
 
   public void setSalary(double newSalary) {
      if(newSalary >= 0.0) {
         salary = newSalary;
      }
   }
 
   public double computePay() {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Now, you study the following program carefully and try to determine its output −

/* File name : VirtualDemo.java */
public class VirtualDemo {

   public static void main(String [] args) {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
      System.out.println("Call mailCheck using Salary reference --"); 
      s.mailCheck();
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
   }
}

This will produce the following result −

Output

Constructing an Employee
Constructing an Employee

Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.

While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.

mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

Tuesday, April 14, 2020

What is Polymorphism in Java? Overriding or Overloading?

Polymorphism vs Overloading vs Overriding


Someone asked me What are the difference between Polymorphism and Overriding in Java and the similar difference between Polymorphism and Overloading. Well, they are not two different things, Polymorphism is an object oriented or OOPS concept like Abstraction, Encapsulation or Inheritance which facilitate the use of the interface and allows Java program to take advantage of dynamic binding in Java. Polymorphism is also a way through which a Type can behave differently than expected based upon which kind of Object it is pointing. Overloading and overriding are two forms of Polymorphism available in Java.

Polymorphism in Java, Oracle Java Tutorial and Materials, Oracle Java Certification, Oracle Java Prep

Both overloading and the overriding concept are applied on methods in Java. Since polymorphism literally means taking multiple forms, So even though you have the name of the method same in the case of overloading and overriding, an actual method called can be any of those multiple methods with the same name.

Polymorphism vs Overriding


Overriding is a form of polymorphism which is used in Java to dynamically bind method from the subclass in response to a method call from sub class object referenced by superclass type. Method overriding is bonded using dynamic binding in Java.

Suppose you have two methods size() in both base class and derived class and Base class variable is pointing to an object which happens to be subclass object at runtime then method from subclass will be called, i.e. overridden method will be called.

This allows to program for interface than implementation, a popular OOPS design principle because Polymorphism guarantees to invoke correct method based upon the object. Method overriding is key for much flexible design pattern in Java.

Polymorphism vs Overloading


Method overloading is another form of Polymorphism though some people argue against that. In the case of overloading, you also got multiple methods with the same name but different method signature but a call to correct method is resolved at compile time using static binding in Java. Overloading is a compile time activity oppose to Overriding which is runtime activity. Because of this reason overloading is faster than method overriding in Java. Though beware with an overloaded method which creates conflict e.g. methods with only one parameter e.g. int and long etc.

Polymorphism in Java, Oracle Java Tutorial and Materials, Oracle Java Certification, Oracle Java Prep

An example of Polymorphism in Java


Let's see a short example of Polymorphism in Java. In this example, Pet variable behaves polymorphic because it can be either Cat or Dog. this is also an example of method overriding because makeSound() method is overridden in subclass Dog and Cat.

import java.util.ArrayList;
import java.util.List;

abstract class Pet{
    public abstract void makeSound();
}

class Cat extends Pet{

    @Override
    public void makeSound() {
        System.out.println("Meow");
    } 
}

class Dog extends Pet{

    @Override
    public void makeSound() {
        System.out.println("Woof");
    }

}

Let's test How Polymorphism concept work in Java:

/**
 *
 * Java program to demonstrate What is Polymorphism
 * @author Javin Paul
 */
public class PolymorphismDemo{

    public static void main(String args[]) {
        //Now Pet will show How Polymorphism work in Java
        List<Pet> pets = new ArrayList<Pet>();
        pets.add(new Cat());
        pets.add(new Dog());
   
        //pet variable which is type of Pet behave different based
        //upon whether pet is Cat or Dog
        for(Pet pet : pets){
            pet.makeSound();
        }
 
    }
}

Output:
Meow
Woof

In Summary, you can not compare Polymorphism with method overloading or override. Polymorphism is the ability of a variable to behave differently based upon which kind of Object it is referring. They are Java programming language's way to implement polymorphism in language.