I'm getting confused at how java works with everything being a class.
I make a class foo.java
and in the main
method of foo.java
I make an instance of foo
(a class creating itself makes no sense to me but it seems normal in java ?)
Then I make a instance of another class bar
, so I now have instances of foo
and bar
inside the foo
class but how do I access the member variables of foo
with the functions in bar?
foo
is the processing code and bar
is the ui and needs to see all the data in foo
so it can display it.
There are a lot of possibilities. One is to construct foo
with a bar
instance:
public class Foo {
public void someFooMethod() {
}
public static void main(String[] args) {
Foo foo = new Foo();
Bar bar = new Bar(foo);
bar.someBarMethod();
}
}
public class Bar {
private Foo fooLocalRefence;
public Bar(Foo foo) {
this.fooLocalReference = foo;
}
public someBarMethod() {
this.fooLocalReference.someFooMethod();
}
}
You're wrong about "a class creating its self makes no sense to me but it seems normal in java" , because your terminology is wrong. What you are actually doing is to create an instance of class Foo
. And main()
is merely the entry point of the application, because the JVM simply needs to know where to start.
And if you want instances of two different classes to share information, you need to provide one of them with a reference to the other. Something like this:
Foo foo = new Foo();
Bar bar = new Bar(foo);
I suggest you look at the Java tutorials on the oracle site -> http://download.oracle.com/javase/tutorial/java/index.html
Follow these and this will give you a better understanding of how to write applications in Java - writing code which you do not understand will cause you problems later in the development process .....
First, the main
method of Foo
is probably static
, so there is not an instance of Foo
creating a Foo
.
Second, Foo
should expose its data via getter methods and Bar
should access the data by calling the getter methods on the provided instance of Foo
.
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.