【发布时间】:2015-11-20 08:40:56
【问题描述】:
我在使用 this 关键字时遇到了一些问题。如果我有几个类实现另一个类,我如何在不调用类本身的情况下使用它们的值?我解释一下。
//this is my first class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
//getter/setter below
}
//this is my second class
public class Foo2 extends FooHelper{
public double fooDouble;
public float fooFloat;
}
//this is my main method, i'm using it for calling the value.
//I omit all the thrash code before.
//This is how i want to call the method:
//imagine before there are onCreate, activity,...
Foo foo = new Foo().GetFooInt();
//this is the class extended from the firsts
public class FooHelper{
public void GetFooInt(){
//here is my problem, i need to call the Foo class and the fooInt value.
//I want also to be able to edit the Foo object, for example:
if(((Foo)this).getFooInt() == 0){
(Foo) this.setFooInt(5);
}
}
}
这就是我想要实现的,使用扩展类中唯一的 this 关键字访问一个扩展另一个类的类。我该怎么做?
编辑:
我认为我解释得很糟糕。 我的问题是我想访问 FooHelper 中的 Foo 对象,而不是 Foo 对象中的 FooHelper 方法。
例子:
使用此代码后:
Foo foo = new Foo();
foo.HelperClassMethod();
我需要(在 HelperClass 中)访问调用它的 Foo 对象。
public HelperClass<Foo> {
public void HelperClassMethod(){
//HERE i need to use the "foo" object which invoked this method
}
}
我添加了<Foo>,可能我错过了它,这是正确的吗?以及如何在辅助类的方法中使用这个 foo 对象?谢谢大家
EDIT2:我的问题完全失败了,我认为让我们忽略上面的代码并检查以下内容:
我必须在扩展类的方法中访问一个对象。
我有这门课:
public class Foo extends FooToExtend{
public int fooInt;
}
扩展的类是这样的:
public class FooToExtend{
public void MethodOne(){
//HERE i need to access the calling object
}
}
现在,在我的主要活动中,我想这样做:
Foo foo = new Foo();
foo.MethodOne();
我的疑问是如何访问我在 MethodOne 中的 main 中创建的 foo 对象。
我必须在
中更改我的 FooToExtendpublic class<Foo> FooToExtend{
...
}
但我仍然不知道如何访问其中的 foo 对象。
【问题讨论】:
-
Helper 可以用作静力学。也许这对你来说会做得更好?
-
((Foo)this).getFooInt() == null这行不通,你不能比较int和null。 -
老实说,我对此一无所知,因为我不是这个/超级新手的专家。但这是从 Foo.extendedClassMethod 访问名为它的类的最佳方法?我的问题是,因为现在我必须通过我的助手类,我想使用的类(例如,想象我必须做 Foo.GetFooInt(Foo.class)。我想要这个 Foo.class 而不将它作为变量
标签: java android class this extends