It seems you need an instance of the PlayerDetails class (i.e. a PlayerDetails object) in order to call methods on it (unless it's static that is, but I won't go int0 that here). So for example you need to think more along the lines of...
Well, the key is exactly what you pointed out: detailsField belongs to the PlayerDetail class, so it isn't available in the WarGame class.
First of all, the problem with
is that this is the syntax used to access a static variable. You can easily get this to work by adding the keyword "static" to the detailsField declaration:
However, this is not a very good Object-Oriented approach to the problem. A better declaration is this:
However, you need to understand that without the static keyword, you need to create an object from the PlayerDetails class, just like Ben explained. But if you declared it as private like I show above (and you should!), then Ben's solution will still give you a compiler error. One solution is to add a method to PlayerDetails that looks something like this:
(Sorry, I don't know the type used for the variable troops. Please fill in the apprpriate class name or primitive type.)
Wow - thanks guys - that was really helpful! And quick response time too - this forum is great.
Layne - why should I declare the detailsField JTextField as private? I know that stops other classes chaging the value of it or something but I'm not quite sure. I havn't use 'private' once in my whole code - is that something to worry about? I usually just use the default access control.
Joined: Aug 14, 2001
Declaring variables as private and then providing accessor and mutator (getter and setter) methods for them is a practice known as encapsulation and is an important part of object oriented programming. Although you are not required to use it and your code will work without it it is a good practice to get into.
The idea behind it, as I see it, is that by preventing unrestricted outside access (i.e. from other classes) to the variables in the class you can do things like checking for erroneuous values. It provides a clean interface to your class, making it easier to re-use and the design more modular and your classes more robust. Here's an example...
A Person class has a variable called age which is an int. If you allow default or public access to this variable, some code in another class could legitimately do this...
which obviously doesn't make much sense in most cases! So, in Person.java you could do something like this...
then in other classes you would write something like...
hope this helps a little! I know some of this stuff is confusing when you start out, but trust me it does make sense after a while
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com