简体   繁体   中英

OOP interface and base class

This is just for my own knowledge. If a base class "A" implements an interface "I" would any derived classes of A (let's say B) also "is an I" type? In other words "is" keyword returns true? How about class C that is derived from B?

The question is, once you implement an interface in a base class, is that class (and derived classes) stuck being of that interface type? Any way to remove it so "is" return false?

Yes, all derived classes are of type of all their base ancestry.

I'm not sure if there is a way to "remove" base implementation - never tried it. This sounds like your OOD is broken in a major way.

What you might be able to do (and again, never tried it), is to provide your own casting conversion and always return null when trying to cast to that base/interface. Not sure if it'll do the trick (probably won't work when access via reflection).

If a base class implements an interface, all derived classes will also implement that interface. And actually, the fact that any derived class will also implement the interface is a key feature of object oriented programming. (See Liskov substitution principle )

Once you implement an interface in a base class, is that class (and derived classes) stuck being of that interface type?

Yes.

Any way to remove it so "is" return false?

No.

If you need to extend a class that implements an interface without implementing that interface in the new class, the solution is to use encapsulation . Wrap up the base class in your new class and explicitly expose any properties or methods you want to allow access to.

Yes all subclasses will always return true for is when compared to the base or interface. If you want to check if an object is of a specific type, use

if (obj.GetType() == typeof(MyClassName))
{

}

If you want to check a very particular inheritance point, like if an object has some depth of implementation but only so far, just combined is statements like so:

if (obj is FlyingThing && !(obj is Airplane))
{

}

Yes. You can think of inheritance as an "is a" relationship.

class C1 : I {}
class C2 : C1 {}

Can be read as:

C1 is a(n) I . C2 is a C1

Therefore

C2 is a C1 is a(n) I

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