Skip to main content

up casting

up casting
  •  Casting sub class to the super class type is known as upcasting
  •  Upcasting can be done either implicit or explicit.
  • Implicit casting done by compiler.
Up 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
package casting;
 
class Demo1
{
	int k=10;
	void test()
	{
		System.out.println("running test method");
	}
}
 
class Sample1 extends Demo1
{
	double d=12.3;
	void disp()
	{
		System.out.println("running disp method");
	}
}
 
class Run1 extends Sample1
{
	boolean b=true;
	void run()
	{
		System.out.println("running run method");
	}
}
 
public class Upcasting 
{
  public static void main(String[] args)
  {
 
	  System.out.println("********************************");
 
	  Demo1 obj1=new Run1();//up casting
	  //using obj1 you can access demo1 property and its super class
 
	  System.out.println("k value: "+obj1.k);
	  obj1.test();
 
	  //obj1.disp();//error because its subclass property
 
	  System.out.println("********************************");
 
	  Sample1 obj2=new Run1();//up casting
	  //using obj2 you can access property of Sample1 and its super class DeMO1
	  System.out.println("k value: "+obj1.k);
	  obj1.test();
 
	  System.out.println("d value: "+obj2.d);
	  obj2.disp();
 
	  System.out.println("********************************");
   }
 
}
 
output:
 
********************************
k value: 10
running test method
********************************
k value: 10
running test method
d value: 12.3
running disp method
********************************