View Full Version : Noob question: Getting value from another class
Lococard
08-22-2008, 06:25 AM
Heya,
Sorry for this very basic question but.
I have a driver class, which uses 3 other classes to create the objects. (Simulating a trucking company, driver class, vehicle class, route class and trucking company class)
In the route class how would i get a value from a created vehicle?
Each vehicle is rated with a cost per hour value and i need to add the total of all the vehicles on that route.
thanks
brad211987
08-22-2008, 07:27 PM
It may be easier to answer your question if you post your code so we can use that as an example and have it be in context with your application. Here is a smaller example to try and illustrate it though.
We can start by defining two classes, Example1 and Example2. Example 2 will access data from Example1.
public class Example1
{
private String data1 = "this is my test data";
public String getData1()
{
return data1;
}
}
public class Example2
{
public static void main(String[] args)
{
Example1 ex1 = new Example1();
String data = ext.getData1();
System.out.println(data1);
}
}
In this example, when we run the main method of the Example2 class, the first thing it does is create an object of type Example1. We then use this object reference to obtain the value using an accessor method. Accessor methods are simply get/set methods that either set a value, or return a value. We assign the value from the accessor method to the local variable "data". Lastly, we print the value of data, which is the string from the Example1 class.
Hope that helps!
jerry62704
08-22-2008, 10:29 PM
Put them all in the same package and the appropriate classes will be available to you.
There isn't really a single and/or a simple answer to your question. In order words, there are a number of ways to share information between objects...and as such, it all depends on your design and business requirements.
Instead of listing any possible solutions, I think you should describe your requirement better so that we're not left wondering what you meant etc.
Not that I like paraphrasing the following saying, but since it fits the situation so well..I will just write it anyway.
THERE IS MORE THAN ONE WAY TO SKIN A CAT
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.