forked from icterguru/JavaProgrammingA2Z
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectTypeCastingEx2.java
More file actions
67 lines (54 loc) · 2.11 KB
/
ObjectTypeCastingEx2.java
File metadata and controls
67 lines (54 loc) · 2.11 KB
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
package chapter11;
// ObjectTypeCastingEx2.java
class BaseClass
{
public void callMe() //Base class method
{
System.out.println ("Invokes the BaseClass::callMe() method ");
}
}
class DerivedClass extends BaseClass
{
public void callMe() //Derived Class method
{
System.out.println ("Invokes the DerivedClass::callMe() method");
}
public void callMe2() //Derived Class method
{
System.out.println ("Invokes the DerivedClass::callMe2() method");
}
}
public class ObjectTypeCastingEx2{
public static void main (String args []) {
// DerivedClass reference and DerivedClass object
DerivedClass obj1 = new DerivedClass();
//Calls the method from DerivedClass class
System.out.println("Automatic Upcast ....");
obj1.callMe(); // Automatic Upcasting
// Invokes the DerivedClass::callMe() method
((BaseClass)obj1).callMe(); // Upcasting, but....
// Will not invokes the BaseClass::callMe() method
obj1.callMe2(); // Invokes the DerivedClass::callMe2() method
System.out.println();
// BaseClass reference and BaseClass object
BaseClass obj2 = new BaseClass();
// Calls the method from BaseClass class
obj2.callMe(); // Invokes the BaseClass::callMe() method
System.out.println("Tried to Downcast but.... creates a Runtime Error");
// ((DerivedClass)obj2).callMe(); // Tried for Downcasting,
// Okay at compile time but creates Run-time error
// BaseClass reference but DerivedClass object
BaseClass obj3 = new DerivedClass();
//Calls the method from DerivedClass::callMe() class
System.out.println("\nNo effect of casting....");
obj3.callMe(); // Invokes the DerivedClass::callMe() method
((DerivedClass)obj3).callMe(); // Invokes the DerivedClass::callMe() method
((BaseClass)obj3).callMe(); // Still invokes the DerivedClass::callMe()
System.out.println("Please look at here.........................");
// obj3.callMe2(); // Will cause following compile time Error:
// 'The method callMe2() is undefined for the type BaseClass'
((DerivedClass)obj3).callMe2(); // DownCasting is made here
// Invokes the DerivedClass::callMe2() method
System.out.println("DownCasting is made in the above line .......");
}
}