Topic: Java Programming
What is the benefit of assigning a parent reference to a child object since there is a limitation for child class members to be invoked using parent reference? unable to understand this concept of polymorphism and what it adds to programming? can anyone help me?
Author: SANJAY
RANJIT
One way to understand it probably through this way. So, consider a situation where you do not want to tightly couple the type of an object in the code, rather you want it to be decided by the caller of this code. Now you imagine if you have only reference type of child class then once your code says childclass1 cs1 = //object supplied by the caller. In this case you only can supply an object of type childclass1 and never an object of childclass2. This is just a simple aspect but there are other benefits.
VAMSI
Basically the main reason was to make your code more general and reusable. It does this, in part, by reducing the dependencies you code may have on implementation details of other code. Let me explain you with example. myList = new ArrayList();
For example: List
All the code that uses the "myList" variable "does not know" that it's using an ArrayList. It might be using a LinkedList. It might use some new kind of list that has not yet been developed. If someone comes up with a new and better kind of List, your code (after this line) can start using it, with only a change to the particular List implementation class on the right side of that line.This might not seem like a significant advantage, when you're writing small programs, where all your code is in the "main" method. But as you start writing larger programs and using libraries, the benefits become much more significant and important. JDBC, for example, defines interfaces that enable you to work with various databases. Yes, certainly, each database has implementation classes for those interfaces. But you *do not want to* and *do not need to* "hard code" any particular database's implementation classes into your program. You can write your program, based on the interfaces only, and then your program will work with all supported databases.
RANJIT
@sanjay All the variable and method of Parent can be easily access in child class.