views:

1292

answers:

3

In OOP languages like C# or VB.NET, if I make the properties or functions in a super class protected I can't access then in my Form, They can only be access in my class that inherits from that super class.

To access those properties or functions I need to make them public which defeats encapsulation on re-write them in my class which defeats inheritance.

What is the right way to do this?

+2  A: 

If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements.

Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it. The car is no use to me.

Either make those members Public (or at least internal) and use them or ditch the class and use one that gives your consuming code the features it needs.

Perhaps what you are really looking for is an interface. The interface contains the members your code needs and you implement that interface on your class. The advantage here is that your class can determine that the members are being accessed via this Interface rather than an inheriting subclass.

AnthonyWJones
A: 

Sorry, it's not clear what you mean by "in my Form" - what is the relationship between your Form and your two classes? If your classes are controls in the same project, and you want to access properties from the form, you should use the 'internal' keyword.

Benjol
+1  A: 

"need to make them public which defeats encapsulation"

Don't conflate good design with the icky visibility rules. The visibility rules are confusing. There are really two orthogonal kinds of visibility -- subclass and client. It's not perfectly clear why we'd ever conceal anything from our subclasses. But we can, with private.

Here's what's important. Encapsulation does not mean hiding. Protected and private are not an essential part of good encapsulation. You can do good design with everything being public (that's the way Python works, for example).

The protected/private stuff is -- mostly -- about intellectual property management: are you willing to commit (in a legally binding, "see-you-in-court-if-it-doesn't-work" way) to an interface? If your software development involves lawyers, then you care about adding protect and private to the things you're not committed to.

If you don't have to cope with lawyers, consider doing encapsulation right but leave everything public.

S.Lott