What is downcasting in java

What you will learn here about java downcasting

  • What is downcasting in java

Downcasting is one of the important concept in java. So here we are going to see what is downcasting in java.

What is downcasting in java

When Subclass type refers to the reference of Parent class, it is known as downcasting. If Subclass type refers directly to the object of parent class then compiler gives Compilation error ( ClassCastException is thrown at runtime ).
what is downcasting in java
ClassCastException is thrown when we are trying assign parent class object to child class reference which is shown below.
ClassCastException  downcasting

Java downcasting example

The Sample java downcasting example is given below.

Parent class Defination

public class Sport {

	String coach()
	{
		return "This is General Coach ";
	}
	
}

Child class Defination

public class Cricket extends Sport{
	
	String coach()
	{
		return "This is Cricket Coach ";
	}

}

Main driver class Defination

public class Game {

	public static void main(String[] args) 
	{
		Sport S=new Cricket();
		Cricket C=(Cricket) S;
		System.out.println(C.coach());
	}

}

OUTPUT

This is Cricket Coach

You may also like...