palapapa
palapapa

Reputation: 959

Why use different type and constructor when instantiating a class?

Suppose we have a class ProductA that inherited another class called Product. What's the meaning of

Product product = new ProductA();

And what's the difference between that and

ProductA product = new ProductA();

Upvotes: 1

Views: 112

Answers (3)

CharithJ
CharithJ

Reputation: 47560

When initializing, no difference. It is just like saying "ProductA is a Product type of thing".

In object-oriented programming, the concept of IS-A is a based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance.

Then under what circumstances can these two syntaxes have a difference?

Why to use Polymorphism?

Why and when use polymorphism?

Additional reading : The difference between virtual, override, new and sealed override

Upvotes: 3

LongChalk_Rotem_Meron
LongChalk_Rotem_Meron

Reputation: 803

A big difference. A context difference. A generality difference. Let me give you a simple example

public class Animal {
 ...
}

and

public class Dog : Animal {
...
}

then if you have a Animal dog = new Dog(); that's not going to expose (in the compile time realm) any additional properties the dog has over the animal. your "dog" is just an animal and as such it should be treated. nothing additional will appear in intellisense auto complete for example. All you want to "know" when you are using this object is therefor limited to it being an animal. if you have a Dog dog = new Dog(); you want (in the compile time realm) to treat it like a dog. It will expose it's full functionality and properties. A dog has a tail, and an animal doesn't for example. Do you want to use "tail" property in your code?

Also suppose you have a DogTender with a TakeCareOfDog(Dog myDoggy) method. If you stated Animal dog = new Dog(); well than the instance of DogTender can't handle your dog (because it's not a dog. It's an animal). However, your animal can fit well in an AnimalCollection (like a Zoo). We call this the Liskov principle or the Substitution principle - the decendant classes tell their base class - "anything you can do, I can do better". Anything an Animal can do, a dog can also do, but not the other way around.

Upvotes: 1

Brian Rasmussen
Brian Rasmussen

Reputation: 116421

There's no difference in the terms of what instance gets created, but there is a difference. In your first example, you can only access members defined by Product.

This is similar to the following.

object x1 = "hello";
string x2 = "hello";

In both cases a string instance is created, but you can call .Length on x2, but not on x1.

Upvotes: 3

Related Questions