Re: classes question



linuxnooby@xxxxxxxxxxxx wrote:
Hi

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();
}
}

problem isn't that hello is invisible. Problem is that it isn't static. You could use either:
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);
}
.



Relevant Pages

  • Re: classes question
    ... objects to interact with each other. ... In the main class I instantiate two other classes, A and B. Class A has ... separate file. ... public static void main{ ...
    (comp.lang.java.help)
  • classes question
    ... 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 ... separate file. ...
    (comp.lang.java.help)
  • Re: Netbeans problem with JPanel
    ... my opinion it should simply be a class that I can instantiate from my ... When you create a new artifact with NetBeans, it gives you a choice of what kind of artifact to create. ... One choice is "Java Main Class", ...
    (comp.lang.java.programmer)