0

What is the difference of creating child class object and upcasting?

  1. SubClass sC = new SubClass(); // instantiating object
  2. SuperClass sC1 = new SubClass(); // Upcasting

What is the sense of the upcasting if you can access all functions in superclass and subclass when you create a subclass object?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • If the subclass has additional methods, you cannot access them with the second example (at least, not without casting). – Mark Rotteveel Apr 02 '23 at 07:57
  • In example 2. you are telling yourself and who reads your code that they should not care about the concrete/runtime type of `sC1` as long as they know that it is some `SuperClass`. It’s called abstraction, and it’s a key concept in programming and software development. So you’re asking a good question. And obviously one that has been asked before. – Ole V.V. Apr 02 '23 at 08:22

0 Answers0