不能让静态引用非静态方法 [英] Cannot Make Static Reference to Non-Static Method

查看:210
本文介绍了不能让静态引用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建立在Java多语言的应用程序。

Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:

public static final String TTT =  (String) getText(R.string.TTT);

这是错误消息:

错误:无法使从类型的静态引用非静态方法的getText(INT)        背景

Error: Cannot make a static reference to the non-static method getText(int) from the type Context

在此先感谢。

推荐答案

由于gettext的非静态的,你不能从一个静态方法调用。

Since getText is non-static you cannot call from a static method.

要理解为什么,你要明白这两个的区别。

To understand why, you have to understand the difference in the two.

实例(非静态)方法在属于特定类型(类)的对象的工作。这些都与新的像这样创建的:

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

要调用一个实例方法,你把它的实例(myObject的):

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

然而一个静态方法/字段可以被称为直接的类型,这样说: 的previous说法是不正确的。 你也可以参考静态字段与对象引用类似 myObject.staticMethod()但这不提倡,因为它没有说清楚,他们是类变量。

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

和两者不能同时工作,因为他们在不同的数据空间(实例数据和类数据)进行操作。

And the two cannot work together as they operate on different data spaces (instance data and class data)

让我自愧不如。考虑这个类(伪code):

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

现在,我有以下的用例:

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

什么是价值观?

What are the values?

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

在换句话说TTT是受该类型的所有实例共享一个基准。因此,它毫无意义地说。

In other words TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

所以,问题是为什么是的 TTT 的静态或为什么的getText()不是静态的?

So the question is why is TTT static or why is getText() not static?

消除静电,它应该让过去这个错误 - 但没有理解你的类型做这只是一个橡皮膏,直到下一个错误。什么是对的getText需要它是非静态的要求?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText that require it to be non static?

这篇关于不能让静态引用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆