How to Choose Between Private and Protected Access Modifier to Encapsulate Members Between Base and Childs Classes

How to choose between private and protected access modifier to encapsulate members between base and childs classes?

Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?

When you call a public method on a class, that method can access private members of that class:

public class Foo
{
public void Bar()
{
Baz();
}

private void Baz()
{
// private method called by public method
}
}

var foo = new Foo();
foo.Bar();

This compiles just fine. Your setter is the same: it's public, so callable from everywhere, even if it accesses private members.

As for making your field (private long id = -1;) protected: yes, that will mean you can access it in derived classes. But whether you want to is another question.

You have declared a public property for a reason. Perhaps you want to do some validation in its setter or getter. If not, if you're just using a property to access a private field, you could just ditch the entire private field and use an auto-implemented property:

public long ID { get; set; } = -1;

Then you can access the property everywhere, from within itself, from derived classes and from code using this class.

See also:

  • What is the difference between a field and a property?
  • What are Automatic Properties in C# and what is their purpose?

What is the difference between public, protected, package-private and private in Java?

The official tutorial may be of some use to you.

















































ClassPackageSubclass
(same pkg)
Subclass
(diff pkg)
World
public+++++
protected++++
no modifier+++
private+

What is the difference between private and protected members of C++ classes?

Private members are only accessible within the class defining them.

Protected members are accessible in the class that defines them and in classes that inherit from that class.

Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.

Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.

What is the difference between public, private, and protected inheritance in C++?

To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".

There are three accessors that I'm aware of: public, protected and private.

Let:

class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
  • Everything that is aware of Base is also aware that Base contains publicMember.
  • Only the children (and their children) are aware that Base contains protectedMember.
  • No one but Base is aware of privateMember.

By "is aware of", I mean "acknowledge the existence of, and thus be able to access".

next:

The same happens with public, private and protected inheritance. Let's consider a class Base and a class Child that inherits from Base.

  • If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.
  • If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.
  • If the inheritance is private, no one other than Child is aware of the inheritance.

How to limit protected member to be accessible from only first level child C#

If you have a specific MiddleClass that should have privileged access to a member of TopClass, you can put MiddleClass in TopClass as a nested type. Nested types have access to all members of their enclosing type.

public class TopClass
{
private string ThisIsOnlyAccessibleForTopClass { get; set; }
private string ThisIsOnlyAccessibleForTopClassAndMiddleClass { get; set; } // I want this to be accessible only by the MiddleClass
public string AccessibleFromEverywhere { get; set; } // this is good as it is public so accessible everywhere

public virtual void SomeWeirdFunction()
{
ThisIsOnlyAccessibleForTopClass = "I can access this here as it is grand father's private member!";
}

public class MiddleClass : TopClass
{
public override void SomeWeirdFunction()
{
base.ThisIsOnlyAccessibleForTopClassAndMiddleClass = "As this is a MiddleClass class, I am accessible here.. That is good!";
}
}

}

public class BottomClass : TopClass.MiddleClass
{
public override void SomeWeirdFunction()
{
// compilation error:
// base.ThisIsOnlyAccessibleForTopClassAndMiddleClass = "I don't want this to be accessible here!";
}
}

If you have one or more MiddleClass classes in the same assembly as TopClass, and all the BottomClass classes are going to be in another assembly, you can use private protected. It means "access to only classes that are BOTH internal and protected", whereas protected internal means "access to classes that are EITHER internal or protected".

// in Assembly A

public class TopClass
{
private string ThisIsOnlyAccessibleForTopClass { get; set; }
private protected string ThisIsOnlyAccessibleForTopClassAndMiddleClass { get; set; } // I want this to be accessible only by the MiddleClass
public string AccessibleFromEverywhere { get; set; } // this is good as it is public so accessible everywhere

public virtual void SomeWeirdFunction()
{
ThisIsOnlyAccessibleForTopClass = "I can access this here as it is grand father's private member!";
}
}

public class MiddleClass : TopClass
{
public override void SomeWeirdFunction()
{
base.ThisIsOnlyAccessibleForTopClassAndMiddleClass = "As this is a MiddleClass class, I am accessible here.. That is good!";
}
}

// in Assembly B, which references Assembly A

public class BottomClass : MiddleClass
{
public override void SomeWeirdFunction()
{
// compile error
// base.ThisIsOnlyAccessibleForTopClassAndMiddleClass = "I don't want this to be accessible here!";
}
}

I don't understand inheritance with base classes

Example you given invlolves interface IDisposable. In C#, class can implement multiple interfaces.

On the other hand, in C# class may inherit from exactly one class.

Having said that, it is not always good idea to inherit from classes, as it very limiting. Instead I would suggest composition: wiki

For example, I would suggest something like composition design pattern (it is a small variation, as the composite does not have collection of objects, rather just one object):

public interface IFoo
{
void DoFooStuff();
}

public class Foo : IFoo
{
public void DoFooStuff() {...};
}

public class ShouldImplementFoo : IFoo
{
// Composition, you need to initialize it some time
private Foo _foo;

public void DoFooStuff() { _foo.DoFooStuff(); }
}

EDIT

After rethinking your problem, you seem to want to put some set of objects (of different classes) in a list, so you can execute some defined action on each object in a list.

The simpliest is: define interface with your defined action:

public interface IMyIntf
{
void MyDesiredAction();
}

And now, make all classes implement it. Now you might think "Well, now I need to implement this method everywhere..." - nothing like that! Just use adapter design pattern, for example, having class:

public class MyConcreteClass
{
public void ActionIWishToExecuteOnThisObject()
{ ... }
}

you just modify it to:

public class MyConcreteClass : IMyIntf
{
public void ActionIWishToExecuteOnThisObject()
{ ... }

// implement interface
public void MyDesiredAction()
{
ActionIWishToExecuteOnThisObject();
}
}

Now, you can use some aggregate, like List<IMyIntf>, place all objects you are interested in there and do:

foreach(var item in myList)
item.MyDesiredAction();

Reasons to use private instead of protected for fields and methods

There is some consensus that one should prefer composition over inheritance in OOP. There are several reasons for this (google if you're interested), but the main part is that:

  • inheritance is seldom the best tool and is not as flexible as other solutions
  • the protected members/fields form an interface towards your subclasses
  • interfaces (and assumptions about their future use) are tricky to get right and document properly

Therefore, if you choose to make your class inheritable, you should do so conciously and with all the pros and cons in mind.

Hence, it's better not to make the class inheritable and instead make sure it's as flexible as possible (and no more) by using other means.

This is mostly obvious in larger frameworks where your class's usage is beyond your control. For your own little app, you won't notice this as much, but it (inheritance-by-default) will bite you in the behind sooner or later if you're not careful.

Alternatives

Composition means that you'd expose customizability through explicit (fully abstract) interfaces (virtual or template-based).

So, instead of having an Vehicle base class with a virtual drive() function (along with everything else, such as an integer for price, etc.), you'd have a Vehicle class taking a Motor interface object, and that Motor interface only exposes the drive() function. Now you can add and re-use any sort of motor anywhere (more or less. :).

Private vs Protected - Visibility Good-Practice Concern

No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.

If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.

A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.

Encapsulation in the Java Model Class

Protected modifier

The common practice it to use protected access modifier to encapsulate class members within the Parent class.

Package private fields and methods will not be visible to subclasses located outside the package of the Parent class. Conversely, protected variables and behavior will be accessible to any subclass regardless of its location.

Composition vs Inheritance

Inheritance is not always beneficial, in-fact there are many cases where it isn't. You need to consider all pros and cons before making class-design decisions like whether a particular class will derive from another class.

What are the benefits of extending the BaseModel?

It doesn't feel like you can take advantage from the polymorphism here. Because the only behavior you can use with the parent type BaseModel are getters and setters for dates of creation and update. And at the same time you'll not be able to access the specific behavior of subclasses.

It looks rather as a drawback because BaseModel isn't designed for extension. I.e. it neither contains any useful implementations (I'm not taking getters/setters into account), no abstract methods are meant to be implemented by its subclasses (that would be a scenario of advantageous polymorphism).

In fact, you are extending BaseModel just in order to reuse a couple of variables. That not a compelling reason to utilize inheritance.

Your example is a perfect case to substitute an IS A relationship (Post is a BaseModel) with HAS A relationship (Post includes BaseModel).

The design technic, when a class contains its instance field an instance of another class instead of extending this class, is called Composition.

As a general rule, composition is a more preferable approach than inheritance. As well as inheritance, it allows to reuse the behavior and at the same time it classes closely coupled.

If you make the BaseModel a concrete class and apply composition to other classes, your code will look like that.

public class BaseModel {
private String id;
private LocalDateTime createdDate;
private LocalDateTime updatedDate;
// getters and setters
}

public class Post {
private BaseModel base;
private String slug;
private String name;
private String title;
// other fields, getters and setters
}

public class Category {
private BaseModel base;
private String name;
private String slug;
// other fields, getters and setters
}


Related Topics



Leave a reply



Submit