简体   繁体   中英

Can a class's ivar be an instance of its superclass?

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.

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.

Yes, that's good. You can have any type of ivars in any class, basically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM