Tuesday, 30 August 2016

Method Overriding Rules In Java

Method overriding rules Java


Parameters that need to consider in method overriding is,

What is Method Overriding?

In case of Inheritance, where Parent-child relationship exist, 
Parent class define a method say connect() which does connection to some remote service. 
Child class has better way to do connection than Parent class and don't want to use Parent class connect() method, So it overrides Parent's class connect() method by providing own implementation of connect() method, 

Now whenever connect() method is called using Child class object, then connect() method of Child class will be called and not the connect() method of Parent/Super class, this concept is called Method overriding.

Example of Method Overriding: 
class Parent{
 public void connect(){  
  System.out.println("Doing connection in Parent way");  
 }
}

class Child extends Parent {
 @Override
 public void connect() { 
  System.out.println("Doing connection in Child way");
 }
}

Rules of Method Overriding


Parameters that need to be consider in case of Method Overriding,
  1. Access Specifier of method
  2. Return Type of method
  3. Name of method
  4. Arguments/Parameters of method
  5. Exception that method throws. 

Access Specifier of method
Overriding method in Child class can either have same access specifier as that of Parent class method or can increase visibility but cannot decrease it.

If Parent class method is declared as,
protected void connect(){}
then valid access specifier for Child class overriding method connect() is, 
public void connect(){} OR
protected void connect(){}


Return Type of method:
Overriding method in Child class can either have same return type or should be Subclass of return type declared in method of Super class.

If Parent class method is declared as,
protected Number connect(){}

then valid Return type for overriding connect() method in Child class is either Number class or all subclass of Number class, 
public Integer connect(){}
protected Long connect(){}
protected Number connect(){}

Name of method:
Name of the overriding method in Child class must be exactly same as that of method declared in Parent Class


Arguments/Parameters of method: 
Total number and Type of arguments present in overriding Child class method must be exactly same as that of Parent class method.

Note:
Arguments present in Child class method should be exactly of same type (Subclass will not work) as that of Parent class method.
Why Subclass argument won't work, Let's understand it with below example,
class A1{}
class A2 extends A1{}
class A3 extends A1{}

class Parent{
 protected Number connect(A1 a1){  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }
}

class Child extends Parent {
 @Override
 public Long connect(A2 a2) { 
  System.out.println("Doing connection in Child way");
  return null;
 }
}
In above example,
Super class connect method take generic agument A1.
Child class overriding connect method take specific agument A2

If Covariant parameters are allowed in Method overriding than what will be output of below lines,
Parent p = new Child();
p.connect(new A3());

Above line will call connect() method of Child class method due to Polymorphic behaviour. Also, According to Parent class method definition it should work but according to Child class overriding definition it will not work.

This problem occurred because Child class overriding method accepted specific(Subclass) argument compared to Parent class method which is accepting generic argument.

To avoid this situation, parameter in overriding method must be exactly same. 


Exception that method throws: 

Unchecked Exception:  
Overriding method in Child class can throw any number of Unchecked Exception irrespective of Parent class overriden method has declared any Checked/Unchecked Exception or not.  
Below example shows valid overriden method connect() and connect1().
class Parent{
 protected Object connect(String s1) {  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }

 protected Object connect1(String s1) throws NullPointerException{  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }
}

class Child extends Parent {
 @Override
 public Integer connect(String s2) throws RuntimeException, NullPointerException{ 
  System.out.println("Doing connection in Child way");
  return null;
 }

 @Override
 protected Object connect1(String s1) throws RuntimeException{  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }

 public static void main(String[] args) {
  Parent p = new Child();
  p.connect("hello");
 }
}


Checked Exception:  
If say Overriden method of Parent class throws IOException, then overriding method in Child class can either throw 
  1. No Exception,
  2. Same IOException,
  3. Any number of Subclass of IOException like FileNotFoundException, EOFException etc.


Not Allowed:
If say Overriden method of Parent class throws IOException, then overriding method in Child class cannot throw
  1. It cannot throw exception from totally new inheritance hierarchy like SQLException.
  2. It cannot throw broader exception like Throwable or Exception in our case. 

Conclusion: 
Overriding method of Child class can throw any number of Unchecked Exception irrespective of Overriden method of Super class throwing or not throwing any exception.

If Super class overriden method throws Cheked Exception then Overriding method of Child class can either choose not to throw any exception, or throws same exception or throws any number of subclass of Exception thrown by overriden method

Lets see few example and understand:
class Parent{
 protected Object connect(String s1) {  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }
 
 protected Object connect1(String s1) throws Exception{  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }

 protected Object connect2(String s1) throws IOException, SQLException{  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }
 
 protected Object connect3(String s1) throws IOException{  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }

 protected Object connect4(String s1){  
  System.out.println("Doing connection in Parent way"); 
  return null;
 }

}

class Child extends Parent {
 @Override
 public Integer connect(String s2){ //It will work
  System.out.println("Doing connection in Child way");
  return null;
 }

 protected Object connect1(String s1) throws Exception, FileNotFoundException, MalformedURLException{ //It will work  
  System.out.println("Doing connection in Child way"); 
  return null;
 }
 
 protected Object connect2(String s1) throws FileNotFoundException{ //It will work
  System.out.println("Doing connection in Child way"); 
  return null;
 }
 
 protected Object connect3(String s1) throws Exception{ //It will NOT work  
  System.out.println("Doing connection in Child way"); 
  return null;
 }
 
 protected Object connect4(String s1) throws Exception{ //It will NOT work  
  System.out.println("Doing connection in Child way"); 
  return null;
 }
 
 public static void main(String[] args) {
  Parent p = new Child();
  p.connect("hello");
 }
}


In case if you like to try program using different Exception hierarchy, here is Exception hierarchy tree.


You may also like to see


Advanced Java Multithreading Interview Question-Answer.

How is ambiguous overloaded method call resolved in java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

Type Casting Interview Questions In Java

Interface interview questions and answers in Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Sunday, 7 August 2016

Find the number of Islands using DFS.

Count total number of Islands OR
The "Island Count" Problem


Given a Ocean in a form of 2D matrix as shown below in which there are few Island present 
(or may not be present).

In a matrix given above, which has only two values ‘1’ and ‘0’. 
1 represents land and 
0 represents water, 
Find the total number of Islands.

Lets understand what is the input and the expected output with few samples.

Sample 1:
Input: 
        int[][] island = new int[][] {
                { 1, 1, 0, 0, 0 },
                { 0, 1, 0, 0, 1 },
                { 1, 0, 0, 1, 1 },
                { 0, 0, 0, 0, 0 },
                { 1, 0, 1, 0, 1 }             
        };
Output: 5

Sample 2:
Input:
        int[][] island = new int[][] {
                {0, 0, 0, 0, 0 },
                {0, 0, 0, 0, 0 },
                {0, 0, 0, 0, 0 },
                {0, 0, 0, 0, 0 },
                {0, 0, 0, 0, 0 }               
        };

Output:0

Sample 3:
Input:
        int[][] island = new int[][] {
                { 1, 0, 0, 0, 0 },
                { 0, 1, 0, 0, 0 },
                { 0, 0, 1, 0, 0 },
                { 0, 0, 0, 0, 0 },
                { 1, 1, 1, 0, 0 }                  
        };

Output:2

Saturday, 6 August 2016

Find the number of Islands

Count number of islands where every island is row-wise and column-wise separated


Count total number of islands present in given matrix where every island is separated row-wise and column-wise.

Given a rectangular matrix which has only two values ‘1’ and ‘0’.
1 represents land.
0 represents water.
Islands are all rectangular in shape that is values ‘1’ will always appear in form of rectangular islands and these islands are always row-wise and column-wise separated by at least one line of ‘0’s.

If there is any diagonal island then it will be considered adjacent islands and will be separate.
Count total number of islands in the given matrix.


Lets understand what is the input and the expected output.

Sample 1:
Input: 
        int[][] island = new int[][] {
            { 0,  0,  0 },
            { 1,  1,  0 },
            { 1,  1,  0 },
            { 0,  0,  1 },
            { 0,  0,  1 },
            { 1,  1,  0 }               
        };
Output: 3

Sample 2:
Input:
        int[][] island = new int[][] {
            { 1,  0,  0 },
            { 0,  1,  0 },
            { 0,  0,  1 },
            { 0,  1,  0 },
            { 1,  0,  0 },
            { 0,  1,  0 }               
        };

Output:6

Sample 3:
Input:
        int[][] island = new int[][] {
            { 1,  1,  0 },
            { 1,  1,  0 },
            { 1,  1,  0 },
            { 0,  1,  0 },
            { 0,  0,  1 },
            { 1,  1,  1 }               
        };

Output:3

Thursday, 4 August 2016

Stock Buy Sell to Maximize Profit

Maximum difference between two elements such that larger element appears after the smaller number. OR
Stock Buy Sell to Maximize Profit.


We are given an array of N integers representing Stock Prices on a single day.
Find maximum profit that can be earned by performing 1 transaction.


We want to find a pair (buyDay, sellDay), with buyDay ≤ sellDay,
such that if we bought the stock on buyDay and sold it on sellDay, we would maximize our profit.


Lets understand what is the input and the expected output.

Sample 1:
Input: [100, 80, 120, 130, 70, 60, 100, 125]
Output: If we buy a stock at 60 and sell at 125 then profit is maximum (65).
 
Sample 2:
Input: [7, 9, 5, 6, 3, 2]

Output: If we buy a stock at 7 and sell at 9 then profit is maximum (2).

Sample 3:
Input: [6, 5, 4, 3, 2, 1] Output: Prices are in decreasing order so there will be no profit as stock prices goes on decreasing. So answer is 0.

Monday, 1 August 2016

The Skyline Problem

Skyline Problem In Java.


A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. 
Now suppose you are given the locations and height of all the buildings as shown on a cityscape below. Write a program to output the skyline formed by these buildings collectively.

Lets simplify the problem statement and understand it correctly,
If there are many buildings in a area as shown in below picture, If same buildings is viewed from distance then what we can see is not all the buildings but the skyline that is borders of all buildings.

You can see skyline of buildings if viewed from a side and remove all sections that are not visible/overlapped.
All buildings have common base and every building is represented by 3 points(left, right, height)

‘left': is x coordinate of building left wall.

‘right': is x coordinate of building right wall
‘height': is height of building.


A skyline is a collection of rectangular strips. A rectangular strip is represented as a pair (left, height) where left is x coordinate of building left wall and height is height of building.

Lets understand what is the input and the expected output. INPUT: You are given a building coordinates as shown below,
int[][] skyscraper = { {2,9,10},  {3,6,15},  {5,12,12},  {13,16,10}, {15,17,5} };

OUTPUT: Skyline Coordinates = { {2,10},  {3,15}, {6,12}, {12,0}, {13,10}, {16,5}, {17,0} }