36.3k views
2 votes
Can an object of a child type be assigned to a variable of the parent type? For example, Card crd; BirthDay bd = new BirthDay("Lucinda", 42); crd = bd; // is this correct?

1 Answer

3 votes

Final answer:

An object of a child type can indeed be assigned to a variable of the parent type in object-oriented programming due to the principle of polymorphism.

Step-by-step explanation:

Yes, an object of a child type can be assigned to a variable of the parent type. This concept is known as polymorphism, which is a core principle in object-oriented programming. In the example given, BirthDay is presumably a subclass of Card, so you can indeed assign a BirthDay object to a Card variable: crd = bd;. This is correct because the is-a relationship is satisfied—every BirthDay instance is also an instance of Card.

User Ela Buwa
by
8.2k points