"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
abalfazl hossein wrote:
pet is an instance of a Cat,Because of new Cat,Then Why does it need to cast?
abalfazl hossein wrote:pet is an instance of a Cat,Because of new Cat,Then Why does it need to cast?
abalfazl hossein wrote:These returns true, Then again: Why does it need to cast?
abalfazl hossein wrote:Is it possible one object has two kinds?!
Because in that code pet has two kinds!
By "two", I presume you mean three.abalfazl hossein wrote:Is it possible one object has two kinds?!
Because in that code pet has two kinds! Again: Why does it need cast?. . . .
That makes two.Matthew Brown wrote:A Cat is an Animal. If something is a Cat, it must also be an Animal.
abalfazl hossein wrote:
view plaincopy to clipboardprint?
Pet pet = new Cat(“Alley”, 7);
pet.eat(); //no cast needed
((Cat) pet).sleep(); //cast is needed
pet is an instance of a Cat,Because of new Cat,Then Why does it need to cast?
At compile time all the compiler knows is it is a Pet. A Pet does not know how to sleep, the method is specific to Cats. (Please don't quote this without context ;-)).
b is eating
b is eating
Polymorphism. It's still a "b".abalfazl hossein wrote:
b is eating
b is eating
Why are these same?
abalfazl hossein wrote:
It must print:
a is eating
Because Of type cast, Why it doesn't?
abalfazl hossein wrote:
By this order, test became a.
a.eat must print a is eating
No.abalfazl hossein wrote: . . . But it is not possible to cast subclass to super class, . . ..Right?
Does it really? I don't think it does. Have you tried it?abalfazl hossein wrote:
Yes, but . . .It shows polymorphism too. Right?
What you have shown is very different from Ryan Beckett's code you quoted earlier. You should create as many objects as you need, and you should avoid casting as much as possible.If you compare this code to another:https://coderanch.com/forums/posts/list/531088#2408422
Which one is better?Cast or create new instancne?