Java – Object Oriented Programming – Polymorphism

one method name used across multiple methods with the difference in datatypes, or number of arguments, when called based on the arguments used as inputs, the methods are picked up.

Example 1:

parent class:

//Polymorphism
//Compile time polymorphism
//object overloading
//different in data types and diff number of arguments
public class Calculator
{
public static void main(String[]args)

{
Calculator calc =new Calculator();
calc.add(10, 20);
calc.add(10, 20, 30);
calc.add(10, 20, 30.5f);
}

public void add(int a1, int a2)
{
System.out.println(a1+a2);

}
public void add(int a1, int a2, int a3)
{
System.out.println(a1+a2+a3);
}	
	
public void add(int a1, int a2, float a3)
{
System.out.println(a1+a2+a3);
}
}
// object overriding
//run time polymorphism

public class Scicalc extends Calculator
{
public static void main (String[]args)
{
Scicalc scicalc = new Scicalc();
scicalc.add(100, 100);
}
//intentional addition of the below method to override the parents method add
public void add(int a1, int a2)
{

if (a1>100 && a2 >100)
{
System.out.println(a1+a2);
}
else
{
System.out.println("Please enter numbers greater than 100");

}
}
}

Example 2:

//if class made as final, it cannot be inherited, remove the final in the next line to be inherited by child class.

public final class Parent3
{
//final keyword is to make sure the //variable is not updated in the child class	
//child class uses only the parent class //value and is not overridden
final int pocket_money =5;
public static void main(String[]args)
{
Parent3 parent3 =new Parent3();
parent3.watchTV();
}

public final void watchTV()
{
System.out.println("LG");
}
}

Below is child class

//method overriding
//dynamic binding
//run time polymophism - on an inheritance //code 
public class Child3 extends Parent3
{
public static void main (String[]args)
{
//regular mode of creating an obj in parent class
//Parent3 parent3 = new Parent3();
//Parent object reference for a child object
// parent obj ref can only call method of a //child class which is also in the parent //class
Parent3 parent3 = new Child3();
parent3.watchTV();
//parent3.coding();
//Child3 child3 = new Child3();
//child3.watchTV();
//new Child3().watchTV();
System.out.println(parent3.pocket_money);
//to check the value cannot be assigned to alreay declared final
//parent3.pocket_money=10;
}
//public void watchTV()
//{
//System.out.println("Smart TV");
//}

public void coding()
{
	System.out.println("coding");
}
}

Collection

First let’s see the collections advantages over array

  1. Continuous memory
  2. Unused memory will be wasted
  3. cannot say the array size upfront

Collection is basically called a collection of objects Interfaces – all are contracts

  1. Set – ex: playing cards – no order is maintained- no duplicate elements are present
  2. List – ex: Grocery list – insertion order- can have duplicates!
  3. Map