Re: classes question
- From: Mishagam <noemail@xxxxxxxxxxxx>
- Date: Thu, 27 Apr 2006 01:10:46 GMT
Mishagam wrote:
linuxnooby@xxxxxxxxxxxx wrote:And of course a defined in main() method isn't visible anywhere but main() method. Method variables are not visible outside methods, I think even for anonymous classes defined inside methods.Hiproblem isn't that hello is invisible. Problem is that it isn't static. You could use either:
I am starting my first Java program and I have a question about getting
objects to interact with each other.
In the main class I instantiate two other classes, A and B. Class A has
a public variable. But I cannot access this public variable from within
class B. If I make Class A public , the variable becomes visible from
within A, but I get a message saying that class A should be in a
separate file.
Does this mean all the classes have to be put in separate files, or is
there a way of making the variable visible to class B?
code below
cheers David
package talk;
class A {
public String hello = "Hello World";
A(){
}
}
class B {
B() {
System.out.println(a.hello);
}
}
public class test {
public test() {
}
public static void main(String[] args) {
test test = new test();
B b = new B();
A a = new A();
}
}
class A {
public static String hello = "hello world";
}
class B {
B() {
System.out.println(A.hello);
} }
A instead of a as you used.
Or, in you case, you could create instance of A and use form
B() {
System.out.println((new A()).hello);
}
or
B() {
A a = new A();
System.out.println(a.hello);
}
.
- Follow-Ups:
- Re: classes question
- From: linuxnooby
- Re: classes question
- References:
- classes question
- From: linuxnooby
- Re: classes question
- From: Mishagam
- classes question
- Prev by Date: Re: Java won't render.
- Next by Date: Re: classes question
- Previous by thread: Re: classes question
- Next by thread: Re: classes question
- Index(es):
Relevant Pages
|