Getting confused with Reference Casting and Widening w.r.t Objects in java -


I understand the concept of intersection with primitives and their rapper. But in relation to other things, I am confused with extensive and underlying casting. As the example

  class animal {} class dog provides animals {public static zero main (args string []) {dog d = new dog (;); D.go (d); } Void go (animal a) {}}  

Edit: The question is, who has widened one or casting and why?

(in my opinion) if casting is not required, then do not do that. Your code will be more readable.

Specifically, syntax:

  d.go (d);  

is more concise, and as appropriate

  d.go ((animal) d); In fact, in my first attempt to answer my question, I took advantage of being widened due to the reasons mentioned below.  

Okay, it depends on the code you want to complete.

If you want a function that can deal with any kind of animal, dog or otherwise, then you should take input as an animal.

If you want something to do to work, that is only for dogs, or it is understood only as an operation which takes the dog as input, So you should take it as a dog input.

Edit: A more customized example will likely explain why this is not a question with a straightforward liberal answer. All objects in Java are child of the object, and in this way, any method can be written that it takes a parameter object foo . Sometimes this can be useful, but the use of it is actually quite restrictive, you are limited to the methods defined on the object .

It seems that you know about dog , whatever is the object . Instead of scanning an example as a object of dog , you get some property specific to dog You may wish. Basically, if you need to make sure that the arguments of some functions correspond to some contract, then you should reasonably restrict those arguments - which is a bit different: If you need to know that It's a dog, then it's announced to be a dog .

As a general rule, you should choose (in my opinion) the "most elaborate" type that confirms the contract to fulfill you. If you need to know that it is an animal, then it is declared to be an animal .


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -