[英]As java doesn't have referencing, how does one pass information between two separate classes?
非常抱歉,我確實不知道如何命名此問題。 如果有人有更好的選擇,請隨時編輯。 關於我的問題
public class Foo()
{
String name;
public Foo()
{
Bar temp = new Bar();
}
}
public class Bar()
{
public Bar()
{
setFooName("newName");
}
public void setFooName(String name)
{
// Is it possible call a method in Foo?
}
}
public class test {
static public void main(String[] args)
{
Foo foobar = new Foo();
}
}
我對Java還是很陌生,所以我不確定這是否可能,但是使用C ++時,通常會在'Boo'類中使用'Foo'的局部變量,然后將對該對象的引用傳遞給Bar的構造函數,然后將其分配給Bar中的局部變量。
由於java沒有引用,因此我對此事感到困惑。 我要這樣做的原因是我擁有的示例是我需要在類內部創建一個GUI對象,然后將來自GUI對象的信息發送回創建它的類中。
我確實希望一切都有意義,如果沒有,對不起。
我認為您正在陷入困境。
以下示例通過Bar
的構造函數將Foo
引用的副本傳遞給Bar
。 現在,這使Bar
可以訪問Foo
實例的屬性。 它不允許您做的是在兩個引用之間進行更改(即在bar中分配新的Foo
引用不會更改先前的引用)
public class Foo()
{
String name;
public Foo()
{
Bar temp = new Bar(this);
}
}
public class Bar()
{
private Foo foo;
public Bar(Foo foo)
{
this.foo = foo;
setFooName("newName");
}
public void setFooName(String name)
{
// Is it possible call a method in Foo?
}
}
public class test {
static public void main(String[] args)
{
Foo foobar = new Foo();
}
}
然后Bar
可以調用Foo
提供的任何修飾符,並且它將為每個引用該實例的人更改Foo
那些單獨屬性...
我希望這接近您的要求:P
實際上,您可以使用Java執行此操作。 Java有引用,但沒有指針。 令人困惑的是,對於C ++愛好者,這些引用可以為null。
這意味着您當然可以執行以下操作:
public class Bar {
private Foo foo;
public Bar(Foo foo) {
this.foo = foo;
}
public setFooName(String name) {
foo.setName(name);
}
}
public class Foo {
private String name;
public Foo() {
Bar temp = new Bar(this);
temp.setFooName("fooname");
}
}
但在這種情況下,我不確定為什么您不會只寫:
public class Foo {
private String name;
public Foo() {
this.name = "fooname";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.