Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected fields not visible to subclasses

I'm writing a custom view that directly extends android.view.View. If I try to access fields mScrollX or mScrollY, I see an error that the field "cannot be resolved or is not a field." The source code for android.view.View has mScrollX, mScrollY, and similar variables declared protected. How is it that my direct subclass cannot access protected fields of its parent class? (Classes like ScrollView apparently can.)

P.S. I realize that I can call getScrollX(), but I want to update these fields; calling setScroll() has side effects that I don't want.

like image 713
Ted Hopp Avatar asked Feb 06 '11 21:02

Ted Hopp


People also ask

Can subclasses see protected variables?

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Can protected methods be accessed by subclasses?

protected allows you access from the same package, or parent classes. protected allows access within the same package, or by subclasses. Neither is the case when using a superclass object reference.

Can we use protected in subclass Java?

The protected Keyword While elements declared as private can be accessed only by the class in which they're declared, the protected keyword allows access from sub-classes and members of the same package.

Can protected methods be accessed by child class?

No because the compiler does not know whether b is an instance of B , C , or other external classes.


2 Answers

It's because they are not part of the Android SDK.

Here is the source code for mScrollX:

/**
 * The offset, in pixels, by which the content of this view is scrolled
 * horizontally.
 * {@hide}
 */
@ViewDebug.ExportedProperty(category = "scrolling")
protected int mScrollX;

You will notice the @hide annotation. That means this is not part of the Android SDK. The part of the build process that creates the Android SDK will not include this data member in the stub edition of android.view.View that is in the android.jar file that you are compiling against.

The @hide annotation is used for things that for internal purposes needed to be public or protected but are not considered something SDK developers should be using.

Please find other solutions for whatever problem you are experiencing.

like image 193
CommonsWare Avatar answered Oct 13 '22 09:10

CommonsWare


It's very straight forward: notice the @hide annotation above these variables. It's an Android-specific annotation that hides the fields/methods from the public SDK. That's why you can't access them directly.

Romain Guy mentioned it in this post.

like image 20
Lior Avatar answered Oct 13 '22 09:10

Lior