Re: classes question



linuxnooby@xxxxxxxxxxxx wrote:
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.

In your example code it doesn't. Class A doesn't have a variable at all. So I will just guess a little bit.


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.

A general idea on object-oriented programming is that one does not
expose variables to the public. This is typically part of what is called "information hiding" and is considered a good thing in OOP.

An object is supposed to have full control over the access to its
variables. An object is characterized by having state, identity, and
behavior. Object variables hold an object's state and are therefore a
crucial part of what makes up an object, and "no one" but the object
itself should mess with its state.

From the outside, users of an object should tell an object what they
expect from it, and an object should do that (the behavior part of an
object). This is typically done by using methods.

So, the typical way to change an object's state (one or more of its
variables), is to tell the object to do something via a method.
Typically, the method changes the state as a side effect of doing
something, but it has (unfortunately) also become very popular to
provide methods which just change an object's state, but doing nothing else.

In Java, methods just changing an object's internal variable/state are
called setters. Methods just reporting an object's state/variable are
called getters. By convention their names have a set/get prefix:

public class X {
private int value;
public void setValue(int value) { this.value = value; }
public int getValue() { return value; }
}

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?

No, it means you have to study the Java access modifiers in more detail and come to terms with the fact that hiding access to things is a good thing in object-oriented programming.

/Thomas

--
The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
.