Why would one create a Base Class object with reference to the Derived Class

后端 未结 3 1201
不思量自难忘°
不思量自难忘° 2021-02-06 03:56

I was practicing inheritance, using a test program in C# and I found out that the following statement does not throw an error:

BaseClass baseObj = new DerivedCla         


        
3条回答
  •  暖寄归人
    2021-02-06 04:48

    As per my understanding in java,You are trying to call object of DerivedClass by using BaseClass reference varibale baseobj and this coding scenario is totally valid because it is providing the facility of runtime polymorphism.

    Before runtime polymorphism lets understand the Upcasting. When reference variable of parent class is used to refer the object of child class then it is called as Upcasting

     class A{}
    
     class B extends A{}
    
     A obj= new B // Upcasting.
    

    Runtime Polymorphism is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

    Since you are not overriding show method in derived class,You are not doing runtime polymorphism but simply upcasting and upcasting is useful when we want to resolve the calling to overridden method at runntime.

提交回复
热议问题