While referring concepts of method overloading and overriding I came across a wired combination where correct and deep understanding really helps to do good quality software development and avoid falling into trap while dealing with such code base - whether its for real life projects, learning, certification, quiz or just simple knowledge sharing talks.
1: public class File {
2: public void open() {
3: System.out.println("Simple File Open..");
4: }
5: }
6:
7: public class XMLFile extends File {
8: public void open() {
9: System.out.println("XML File Open..");
10: }
11:
12: //parseXML is additional method which is not available in File Class
13: public void parseXML() {
14: System.out.println("Parse XML File..");
15: }
16: }
17:
18: //Test Program for Overriding
19:
20: public class MyTestFile {
21: public static void main(String args[]){
22:
23: //Objects with Reference Type and Object Type same.
24: File simpleFile1 = new File();
25: XMLFile xmlFile1 = new XMLFile();
26:
27: //Its very clear what will be printed from following code
28: simpleFile1.open();
29: xmlFile1.open();
30:
31: //Trap 1 - Still Managable
32: File xmlFile2 = new XMLFile();
33:
34: //Following will call XMLFile.open version and NOT File.open
35: xmlFile2.open();
36:
37: //Trap 2 - Little Twist
38: xmlFile2.parseXML(); //Fail to compile...you know why because its not available with File class - so one can not invoke it.
39:
40: //Trap 3 - Real Confusion Occurs here..
41: //Adding Overloaded methods
42:
43: public void OrganizeFile(File file){
44: System.out.println("Organizing Simple File..");
45: }
46:
47: public void OrganizeFile(XMLFile xmlFile){
48: System.out.println("Organizing Simple File..");
49: }
50:
51: //Here is a magic
52: MyTestFile testFile = new MyTestFile();
53: testFile.OrganizeFile(simpleFile1); //No Issues
54: testFile.OrganizeFile(xmlFile1); //No Issues
55:
56: //Assume which one will be called here..?? Based on Trap-2 you will say obviously xmlversion..but NO
57: //It will Call File Version and not XMLFile Version...why? ..Check the explanation
58: testFile.OrganizeFile(xmlFile1);
59: }
60: }
Explanation:
In Java choice of which ovarloaded method to call is NOT dynamically decided at runtime. Meaning reference type (not the object type) determines which overloaded method is invoked.
In short, which overridden version of the method to call is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type of the argument passed at compile time.
I Hope this helps!!
Thank You.
No comments:
Post a Comment