It's better to declare public List doSomething(Collection c) than public ArrayList doSomething(ArrayList a). That allows you more flexibility. Your method can accept any type of Collection--after all, what it's doing with that parameter isn't specific to ArrayList, is it? And you're not locking yourself into returning an ArrayList in particular. You can change your implementation to return a LinkedList, and no client code will have to change.
(...)
So you cannot replace the question as OP suggested.HFJ 2/e page 210 wrote:Q: If it’s so good to use polymorphic types, why don’t you just make ALL your methods take and return type Object?
A: Aaah… think about what would happen. For one thing, you would defeat the whole point of ‘type‑safety’, one of Java’s greatest protection mechanisms for your code. With type‑safety, Java guarantees that you won’t ask the wrong object you meant to as of another object type. Like, ask a Ferrari (which you think is a Toaster) to cook itself.
But the truth is, you don’t have to worry about that fiery Ferrari scenario, even if you do use Object references for everything. Because when objects are referred to by an Object reference type, Java thinks it’s referring to an instance of type Object. And that means the only methods you’re allowed to call are the ones declared in class Object! So if you were to say:
Object o = new Ferrari();
o.goFast(); //Not legal!
You wouldn’t even make it past the compiler.
Because Java is a strongly‑typed language, the compiler checks to make sure that you’re calling a method on an object that's actually capable of responding. In other words, you can call a method on an object reference only if the class of the reference type actually has that method. We'll cover this in greater detail a little later, so don't worry if the picture isn't crystal clear.
(...)
Alex Derek wrote: java is a big bitch, but it's also really funny
cor van dijk wrote:I expected an answer that says YES your right or NO "take and return type Object?" means that ....
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
cor van dijk wrote:Thank for your answer.
I expected an answer that says YES your right or NO "take and return type Object?" means that ....
I have always wanted to have a neighbor just like you - Fred Rogers. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|