0
what's the difference? a) Animal dog = new Dog(); b) Dog dog = new Dog();
6 odpowiedzi
+ 4
The difference is that unlike object dog from Animal, object dog from Dog will be able to use the existing members from the Class Dog and Animal at the same time. The dog from the class Animal will only be able to use members from Animal since its the base class, any additions to the class Dog will be ignored by the dog created from the class Animal.
+ 3
Edit: I now know why my comment is receiving down votes.
Animal dog = new Dog();
Dog dog = new Dog();
They would both create a Dog object, which derives from the Animal class. But the object instantiated from Animal wouldn't be able to use the methods etc defined within the Dog class, only only those within the Animal class.
Pablo is right, and I'm still learning :P
+ 1
Hi!
I'm just wondering, shouldn't ...
Animal dog = new Animal();
and not
Animal dog = new Dog(); ?
0
what you are doing here is also termed as casting.
In the a) step.
0
The difference is the public interface used to access the Dog's properties, methods and behaviour.
In the 'Animal dog = new Dog ()' example we are only intetested in treating the Dog as an Animal... meaning we are only interested in what Animal properties and behaviour the Dog has [ Eat(), .Drink(), .Legs] ... not those specific to a Dog derived class [.Bark(), .Fetch()].
🤔
- 4
There is no difference. They both create a Dog object.
syntax a) allows for easier understanding of the code; that Dog is a derived class of Animal. You could even write: var dog = new Dog();