How to change public properties in base class as private in derived class.

S

santel

Hi all,

I have these classes

public class Base
{
private string str;
private string str1;
public string MyStr;
{
get { return str; }
}
public string MySecondStr
{
get { return str1; }
}
}

public class Derived: Base
{
}

What I need is while creating a instance to Derived class, I need to
access only MySecondStr property and I don't want MyStr property. Is it
possible to restrict the MyStr property when accessing the derived
class object. Could anyone help me how to do this?

Thanks in advance
 
J

Joanna Carter [TeamB]

"santel" <[email protected]> a écrit dans le message de (e-mail address removed)...

| I have these classes
|
| public class Base
| {
| private string str;
| private string str1;
| public string MyStr;
| {
| get { return str; }
| }
| public string MySecondStr
| {
| get { return str1; }
| }
| }
|
| public class Derived: Base
| {
| }
|
| What I need is while creating a instance to Derived class, I need to
| access only MySecondStr property and I don't want MyStr property. Is it
| possible to restrict the MyStr property when accessing the derived
| class object. Could anyone help me how to do this?

No, this is not possible. It violates the first principles of OO design. If
you make anything public in the base class, then it has to be public in
derived classes; a derived class is *everything* that the base class is. You
need to rethink your design :-(

Joanna
 
S

Stoitcho Goutsev \(100\)

santel,

Joanna is right. You cannot do that. Even if you could nothing stops the
code using objects of your dericed class to cast them to the base class and
use the public property there.

The best you can do I believe is to declare MyStr proprety virtual, override
it in the dericed class and throw some unsopported-property exception there.

Anyways if you feel the need to hide some member that probaly means your
dericed class is not your base class and shouldn't derive from it. I also
agree that sometimes if doesn't make sense to introduce a whole new branch
in the hierarchy just for a class that doesn fit because of one property .
In the latter case exceptions and good documentation might be better
solution.

Again review your design it might turn out that the new class doesn't have
to inherit from the base one or that you need to add one more level in the
hierarchy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top