Skip to main content

Down casting

DOWN CASTING

  •  Casting super class to sub class type is known as down casting.
  • Down casting should be done explicitly
  • Down casting is possible only on the already up casted object.
Down casting Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package casting;
 
class Demo10
{
 
	int k=10;
 
	void test()
	{
		System.out.println("running test method");
	}
}
 
class Sample10 extends Demo10
{
 
	double d=12.3;
	void disp()
	{
		System.out.println("running disp method");
	}
}
 
class Run10 extends Sample10
{
 
	boolean b=true;
	void run()
	{
		System.out.println("running run method");
	}
 
}
 
class start10
{
 
	void execution(Demo10 arg1)
	{
 
		System.out.println("running execution method");
 
		//using arg1 we can access Demo10 and its super class property 
 
		System.out.println("k value: "+arg1.k);
		arg1.test();
 
 
 
		System.out.println("*************************");
 
                //now suppose we have requirement in which accessing 
                //Sample10 property without creating instance of it. 
		//so we need to do downcasting
 
 
		//upcasting
		arg1=new Sample10();//SAMPLE10 CASTED INTO DEMO10
 
		//down casting
 
            Sample10 rf1=(Sample10) arg1;
          //arg1 is reference of demo10 so we need to cast into Sample10
	  //HERE Demo10 is casted to sample10
 
		System.out.println("d value: "+rf1.d);
		rf1.disp();
	}	
}
 
public class Downcasting 
{
	public static void main(String[] args) 
	{
		start st=new start();
		st.execution(new Sample12());
	}
 
 
}
 
output:
 
running execution method
k value: 10
running test method
d value: 12.3
running disp method