Differences in the visibility of the protected inner class for different packages in different versions of Android

Today I ran into this problem on our Android codebase, which puzzled me and my colleagues a bit. Previously, we had the following class structure:

Foo.java

package test.a; public abstract class Foo extends View { protected abstract class InnerFoo { public InnerFoo() {} } protected class Cog { public Cog() {} } } 

Bar.java

 package test.a; public class Bar extends Foo { private abstract class AbstractInnerBar extends InnerFoo { protected abstract void someMethod(); } private class InnerBar extends AbstractInnerBar { Cog myCog; public InnerBar() { myCog = new Cog(); } protected void someMethod() {} } } 

I understand that this class structure is not necessarily simple, but it worked without problems. However, we recently restructured the package and implemented it elsewhere. So we moved it to another package and had almost the same structure with two different packages.

Foo.java

 package test.a; public abstract class Foo extends View { protected abstract class InnerFoo { public InnerFoo() {} } protected class Cog { public Cog() {} } } 

Bar.java

 package test.b; //This is the only change public class Bar extends Foo { private abstract class AbstractInnerBar extends InnerFoo { protected abstract void someMethod(); } private class InnerBar extends AbstractInnerBar { Cog myCog; public InnerBar() { myCog = new Cog(); } protected void someMethod() {} } } 

It is strange that after a change in some versions of Android we get errors such as: java.lang.IllegalAccessError: tried to access class test.a.Foo$Cog[] from class test.b.Bar$InnerBar . I did not think this would be a problem because Cog provides protected visibility, Bar extends Foo and InnerBar extends InnerFoo . Oddly enough, other versions of Android are working fine (no errors, no visibility). We can solve the problem by declaring Cog public , but this seems like an unnecessary workaround.

We saw a problem on Motorola Moto X (first generation Developer Edition) running Android 4.4.4. We had no problem with Nexus 5 with Lollipop or Nexus S with Android 4.1.2

Can anyone shed some light on this?

+6
source share
1 answer

The absolute class Foo in package a is by default a closed package, you must change its public access specifier to avoid errors. Otherwise, there should be no problem with your Cog class, even if it is protected. Just make Foo public and you're good to go.

  public abstract class Foo{} 
0
source

Source: https://habr.com/ru/post/979430/


All Articles