-2

I'm confused why or when to use downcasting and upcasting and polymorphism.

Please tell me if I am correct or wrong. It would be a great help.

If we say this Gift gift = new Pen(); not only we can leverage the use of polymorphism (if subclass has any overridden methods), but also we will create only one object in the heap, like if further if we say want to access Pen class methods we can just say Pen pen = (Pen) gift; this line can be used to access both superclass methods as well as its own method.

But my point is that here we would not have to create a new object in heap instead we can just downcast.

So, if we say like Gift gift = new Gift() and than we want to use Pen class methods we would need to create object again in heap like Pen pen = new Pen().

Basically instead of creating 2 objects in heap we can just create one object and downcast it later. This not only helps to write an efficient code, but also can leverage the use of polymorphism with well maintained code.

  • 1
    Tip: Casting objects back and forth is often a sign of a poor design in your classes. – Basil Bourque Jul 30 '23 at 19:59
  • @BasilBourque Can you tell me where to learn these things properly and also i need someone so that i can clear my doubts ? I am already learning from Youtube but i need guidance too. – Sourav Karjole Jul 31 '23 at 14:47
  • You cannot become a "machine" in programming, this part might be taken over by AI soon. Coding is a creative process, and like painting you just can learn the basic techniques, but then you have to practice and do life-long-learning on the job. There are online programming classes and automated courses, some of them are free, some are paid. I didn't participate in any of them so I cannot recommend a specific one, but if you search for "code training" or similar, you will find enough results. – cyberbrain Aug 01 '23 at 06:12
  • I also would like to add that [SO] is not the ideal place for learning programming in general, but more to solve specific problems, nuts that are hard to crack for you. – cyberbrain Aug 01 '23 at 06:13
  • Your question doesn't really make sense. You wouldn't create two objects just for the sake of having access to extra APIs. You would create an instance of the derived class, as in your first example, and then cast it to `Pen` if there were `Pen`-only APIs you wanted to call on it. – user207421 Aug 01 '23 at 07:02
  • @cyberbrain you're right, SO is not the best platform to learn coding in general. But the big problem nowerdays is, that all former major forums (just to name Spring as an example) decided to close their doors and move to Stack Overflow - leaving a quick note that from now on the user should go to SO. But SO has much more restrictions in what you are allowed and what not than the former userfriendly communities. That's a big problem and a shame in general. So I will not blame a user who just wants to get information and clarification in any possible way ;) – Slevin Aug 01 '23 at 09:10
  • @cyberbrain Ohh thats fine i myself thought that i can get to learn actual thoughts of others like what they have to say about it, thats why i posted above doubt, to get to know if i am on a right track or need to learn still from different sources correctly. Whole meaning was to just understand the concept. And thanks to reply. – Sourav Karjole Aug 01 '23 at 17:25

1 Answers1

2

You are addressing two related questions: Which interface to use to access an object (for this, I see class also as a kind of interface).

If you know in advance that you will need to access Pen methods, you should type your variable as Pen in the first place. But on the other hand, you should refer to objects by their interfaces (from Effective Java by Joshua Bloch) so if you do not need the access to Pen methods, don't access it via that class.

Your second question is about creating objects to access the classes methods. But this approach is not what object oriented programming is made for: you create a class so you can access the inside data (in the object) only via the classes' methods. So your idea of first creating a Gift instance and then creating a Pen instance again for more methods is less than ideal because the methods of Pen also need more data, that have to be initialized at some point in time (usually at the construction of Pen). Where do you get that data from if you only have a Gift instance available?

If you have the data in the first place, why did you not create a Pen right away?

You could also provide a factory method for Pen that creates a new instance from a Gift instance plus all the extra data necessary for a Pen instance.

This is not always an ideal solution, so the answer to your question is neither yes or no, but: it depends. Depending on the actual problem you want to solve, the best solution to pick could vary, so if you have an actual problem to solve, you should add it to your question to get more advice, or add another question.


UPDATE: (per OPs request)

Can you just tell me why we use Gift gift = new Pen()?

As you do not supply any surrounding code, I cannot name the exact reason, but in the link above you find an explanation why you should use the "least specific" interface.

For this we see classes also as interfaces (with an implementation). Also a method is kind of a contract with the implementer of an interface. So if you use the least specific interface, you do not rely on the actual implementation, but on the contract of the methods of that interface. So you can easily change the implementation later if that is necessary.

A good and very commonly used example for this is e.g. the java.util.List interface. You just want to know that (basically) you are operating on an ordered collection. As "user" of the interface you don't care how the list is ordered, or if it is backed by an array or a linked list (or lazy loaded from a database, etc.). If you used java.util.ArrayList you always have to load everything into an array, or at least pretend that you do that - if you inherit from that class and override methods, and that would be super complex to handle for code maintainers.

Why we use Downcasting?

A good use case for this (but probably not the only one) is: Quite often you have existing code that you want to use that expects objects of a certain class or interface. But the existing class doesn't fit your needs, so you inherit of or implement what is existing and expected. You create a more specific implementation. But you cannot or don't want to change the existing code, so you downcast your implementation to whatever is needed. Often the inherited classes do not even implement new methods, but just override some existing ones.

I want to understand the concept of Downcasting, Polymorphism in Java (Why to use and When to use it)

Polymorphism is not always helpful, the past showed that it also can be a burden, especially for code that is maintained and extended over a longer period of time, but also for new code that is just badly designed. It's hard to give a general advice, but it's good that you try to learn about it.

I would recommend that you read at least the chapter Favor composition over inheritance in the book "Effective Java", but can recommend the whole book. It's not only useful for Java developers, but OOP in general (the examples and specific chapters are Java only).

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
  • Thank you for you response. 1. Can you just tell me why we use Gift gift = new Pen() ? basically as per my knowledge it was used during Polymorphism as there were overridden methods. 2. Why we use Downcasting ? if we can create an object of a particular class to access its methods than why to downcast? . 3. Their is no particular problem i need to solve, but i want to understant the concept of Downcasting,Polymorphism in java(Why to use and When to use it) and also i want to practise these things correctly so that i can use it in future – Sourav Karjole Jul 31 '23 at 14:41
  • I updated my answer. It's kinda hard to not sound opinionated there for me, but I hope that I could stay neutral for most of my post. – cyberbrain Aug 01 '23 at 06:07
  • Thats great!! i will definitely go through the book. – Sourav Karjole Aug 01 '23 at 17:35