Hello all

I have a query,may be silly but i have to clear it.IT IS REGARDING THE UPCASTING.I want to

"when we can invoke the methods of base class using the object of derived class.then what is the need of assigning the subclass object to base class reference."


I mean what is advantages of using that reference in comparison to using subclass object.

You may have multiple subclasses, but in this particular piece of code you don't care which one it is.
Animal a = new Cat(); (or) new Dog(); (or) new Horse(); // etc

a.makeNoise(); // don't care what kind of animal it is

Edited 5 Years Ago by JamesCherrill: n/a

You may have multiple subclasses, but in this particular piece of code you don't care which one it is.
Animal a = new Cat(); (or) new Dog(); (or) new Horse(); // etc

a.makeNoise(); // don't care what kind of animal it is

but suppose we need to call makeNoise() 4 time so what the sense whether we are calling it 4 times using base class reference or using particular object.

If you have 4 subclasses you can use 4 variables, or one variable with the base class reference. It depends on the code and what it is doing.
Another (real life) example:
The base class InetAddress holds IP addresses, and has two subclasses Inet4Address and Inet6Address for IPv4 and IPv6 addresses respectively. Once you have got the IP address of some server you don't care whether it was an IPv4 or IPv6, you just want to use the methods that work for either kind, so you just have one variable and declare it as InetAddress.

If you have 4 subclasses you can use 4 variables, or one variable with the base class reference. It depends on the code and what it is doing.
Another (real life) example:
The base class InetAddress holds IP addresses, and has two subclasses Inet4Address and Inet6Address for IPv4 and IPv6 addresses respectively. Once you have got the IP address of some server you don't care whether it was an IPv4 or IPv6, you just want to use the methods that work for either kind, so you just have one variable and declare it as InetAddress.

Now i got it.Thanks james for your help

This question has already been answered. Start a new discussion instead.