Reputation: 9
If ClassB
is a subclass of ClassA
would it be okay if one of ClassB's
ivars is an instance from ClassA
? Sorry, if this is a dumb question. I just find it confusing how ClassB
inherits from ClassA
but it could own an instance of it.
Upvotes: 0
Views: 71
Reputation: 40211
That's totally fine. A class can even have an ivar of it's own type.
Let's say you have a class Wagon and want to model a train. Your Wagon class probably would have 2 ivars of type Wagon. One that points to the next wagon in the train and an other for the previous wagon.
You could then implement a PassengerWagon subclass of Wagon and it would inherit the Wagon ivars from it's super class. To be clear: you could also only define the ivars (of type Wagon) in PassengerWagon instead of the super class, if you only want to track the neighbors of PassengerWagon instances, but those neighbors can be of any Wagon type.
Upvotes: 1
Reputation:
Yes, that's good. You can have any type of ivars in any class, basically.
Upvotes: 1