Animal
is a class and not an interface?Animal
is one of the ancestor classes of Cat
, assuming that Animal
is even a class an not an interface. In general you use an ancestor class or interface when you don't care about the specific class that has been instantiated because all you want to do is use the methods/properties exposed by the ancestor or interface.There's no such thing as "an instance of an object". The object is the instance and it is an instance of a type. In this case, the type is a class.Simple question, but I'm currently commenting my code and started wondering. Is this correct?
C#:// Creates a new instance of the object Cat, inherited from the class Animal Animal cat = new Cat();
It really depends on what you want to do with that variable. If you want to treat it as aI realized the code might not be right regardless.
Cat cat = new Cat(); work just as fine. Don't know why I put Animal in there in first place. Thought it was the way to write when something was inheriting. Brainfart mixed with newbieness
Cat
, i.e. access those members that are specific to the Cat
type, then you need to declare it as type Cat
. If you intend to treat it as an Animal
, i.e. only access those members common to all types derived from Animal
, then declaring it as type Animal
is OK and probably preferable, because it is an explicit indication that that is how it should be treated, e.g.Animal cat = new Cat();
Animal dog = new Dog();
Animal parrot = new Parrot();
var pets = new[] {cat, dog, parrot};