Super.java
package x.y.z;
public abstract class Super {
public CustomClass a() {
return new CustomClass();
}
public abstract String getName();
public abstract String getDescription();
}
Sub.java
package x.y.z;
public abstract class Sub extends Super {
public String getDescription() {
return "Is a Sub";
}
}
User.java
package x.y.z;
public class User {
private class UseCase extends Sub {
public String getName() {
return "UseCase";
}
}
public UseCase use() {
return new UseCase();
}
}
In another part of my app I try to access new User().use().a()
, and I think this causes the error (it's a compile-time error though).
Trying to compile the above errors:
a() in x.y.z.Super is defined in an inaccessible class or interface
What's causing this error and how do I fix it?
New question
This makes the error disappear for me:
User.java
package x.y.z;
public class User {
private class UseCase extends Sub {
public String getName() {
return "UseCase";
}
}
public Super use() {
return new UseCase();
}
}
Changing the type of User.use()
to Super
"fixes" the error.
Is this a problematic "fix", or will this work fine without any hiccups?
The problem here is that the type that you return from User#use
(ie UseCase
) is private
to the User
class, prohibiting it from being accessed from anywhere outside User
. Modifying UseCase
to be public
instead of private
should fix your issue.
public class UseCase extends Sub {
@Override
public String getName() {
return "UseCase";
}
}
a() in x.y.z.Super is defined in an inaccessible class or interface
Because a UseCase
class, that you are trying to return, is private. Consider the following example, that compiles without errors:
User user = new User();
Sub sub = user.use(); // because of implicit up-casting to Sub (and Sub is public)
sub.a();
If you want to fit these 3 lines into a single expression, you need an explicit cast:
CustomClass custom = ((Sub) new User().use()).a();
Also, as you've already pointed out, you can change the use(...)
method return type to a Sub
or a Super
class, so the following code will work without additional casts:
CustomClass custom = new User().use().a();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.