Android编程中遇到的错误分析(一)

来源:互联网 发布:大疆无人机软件 编辑:程序博客网 时间:2024/04/30 07:41

代码:

public final class MyClass{    public class MyRelatedClass    {      ...    }}public class OtherRandomClass{    public void DoStuff()    {       MyRelatedClass data = new MyClass.MyRelatedClass();     }}

错误:

No enclosing instance of type BitmapEffects is accessible. Must qualify the allocation with an enclosing instance of type BitmapEffects (e.g. x.new A() where x is an instance of BitmapEffects

解决:

给MyRelatedClass加static

原因:

I

n response to the comments about packaging multiple classes in one file: unlike .NET, most implementations of java enforce a strict correlation between the name of public class type and the name of the file the class type is declared in. It's not a hard requirement, but not used a system where the correlation is not enforced. The JLS - 7.6 Top Level Type Declarations says this:

When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.
  • The type is declared public (and therefore is potentially accessible from code in other packages).

See this SO question: multiple class declarations in one file

If you are looking to create a namespace to enclose your related classes, then using static inner classes are what you need. The static declaration does not mean one instnace - they can still be instantiated - the static means that they can be instantiated without needing a reference to the enclosing class. As the enclosing class is just for grouping, and not data, you are safe making it a static. To make it clearer that the enclosing class is just for grouping, you should declare it as an interface, so that it cannot be instantiated and has no implementation details.

Although personally, I would refrain from doing this - in Java, packages are used to enforce a namespace. Using inner classes for this quickly becomes cumbersome. (I have tried it!)