Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access modifiers on properties; why doesn't the following work?

I've run into a compiler error that doesn't quite make sense to me. I have an internal property and I want to restrict its set block such that it is only available through inheritance. I thought this would work:

internal bool MyProperty {
    get { return someValue; }
    protected internal set { someValue = value; }
}

But the compiler says that the access modifier on the set block needs to be more restrictive than internal - am I missing something, or is protected internal not more restrictive than internal?

like image 560
Bradley Smith Avatar asked Dec 15 '10 07:12

Bradley Smith


People also ask

What are the 4 access modifiers?

Access modifiers are keywords that can be used to control the visibility of fields, methods, and constructors in a class. The four access modifiers in Java are public, protected, default, and private.

What are the 3 types of access modifiers?

Simply put, there are four access modifiers: public, private, protected and default (no keyword).

What is considered not an access modifier?

Modifiers in Java fall into one of two groups - access and non-access: Access: public , private , protected . Non-access: static, final, abstract, synchronized, volatile, transient and native .

What access modifier hides properties and methods?

Private members and attributes are completely hidden from outside classes as well as from subclasses. Protected access hides the class's methods and attributes from classes that exist outside of the class's package. This means that classes within the same package can access protected methods and attributes.


1 Answers

protected internal is less restrictive; it is protected or internal (not and) - which therefore additionally allows subclasses from other assemblies to access it. You would need to invert:

protected internal bool MyProperty {
    get { return someValue; }
    internal set { someValue = value; }
}

This will allow code in your assembly, plus subclasses from other assemblies, get it (read) - but only code in your assembly can set it (write).

like image 158
Marc Gravell Avatar answered Sep 20 '22 12:09

Marc Gravell