Re: Learning about Objects
You already wrote the solution in line #14: define the necessary accessor methods in the ObjTest class; here's one of them:
Code:
public String getObjID() { return objID; }
You have to implement the others and you can use them if you have an instantiation of yourr ObjTest class.
kind regards,
Jos
Re: Learning about Objects
Excellent, thank you.
I have created the following and it has given what I want :)
Code:
public String getObj() {
return objID + description + aNumber;
}
and,
Code:
System.out.println(((ObjTest) myObjects[0]).getObj());
Thank you so much, you have saved me a lot of time.
I had already spent a few hours researching this and on the bright side learnt alot about Java that I did not know.
Now to format the output to look better, this should be the easy part :)
Re: Learning about Objects
Here is a handy technique for formatting strings. You can read more about it in the Java tutorials on the Oracle site.
Code:
return String.format("ObjectID(%s): %s %d", objID, description, aNumber);
In the project I work on, we use this a lot for logging purposes. There are some implications to doing so related to performance because these end up in a lot of mainline paths and therefore can impact performance. If you care to understand more, I can elaborate, possibly in a different thread related to Java logging. Heck, maybe it's time for my first blog!
Re: Learning about Objects
Thank you,
For now I have used the following at it has worked how I want it to work, but once completed the project I will review everything to ensure I am happy.
Code:
return String.format("%-8s %-20s %d", objID, description, aNumber);
Re: Learning about Objects
Here's something else that comes in handy: if a PrintStream or a PrintWriter needs to output an object of any type it calls its toString() method and prints that. Every type has such a method, either implemented or ultimately inherited from the Object class. So if you define something like this in your ObjTest class:
Code:
public String toString() { return String.format("ObjectID(%s): %s %d", objID, description, aNumber); }
(I copied that code from the previous reply ;-) and somewhere in your code you do this:
Code:
System.out.println(yourTestObj);
the toString() method is called and you'll see the resulting String on stdout.
kind regards,
Jos
Re: Learning about Objects
If you know that your myObjects array is only going to contain ObjTest objects, then declare it as an ObjTest[].
That'll save you having to do that casting when you;re reading things in the array.