File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Passing variables from class to class (SOLVED) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Passing variables from class to class (SOLVED)" Watch "Passing variables from class to class (SOLVED)" New topic
Author

Passing variables from class to class (SOLVED)

Matt Kohanek
Village Idiot
Ranch Hand

Joined: Apr 04, 2009
Posts: 483

I have been working with java for a few years, and I have never learned how to do this. It has been... problematic.

This will sound like it belongs in struts forum at first, but read to the end please. The basic problem is I do not know how to pass a variable from one class to the next without resetting that variable to null.

Right now I am doing a struts site where you can login, create new user registration, and edit profile. All the info is stored in a database.

When editing the profile, I need to know which user is logged in, because the userID is the primary key, which is needed in the sql statement so it will know which row to alter.

So how can I pass the user variable from one class to another class without resetting either one of the two classes. Obviously I cannot use

Object object = new Object();
object.getUser();

because that sets the Object to all null values.

Do I need to use extends or implements or something like that? I have little experience with those, though I am sure implements will not work because I cant change that class to an interface


True wisdom is in knowing you know nothing - Socrates
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
I think there's a dedicated forum for struts on this site, best look there for more info.

Quick answer: the primary way of passing values from one action to another (I think you are working with struts Action classes?) is to put the values into the request or session (so, first job for you would be to read up on those topics: HttpServletRequest and HttpSession). Struts action classes do their work in the execute() method, and that method has a parameter of type HttpServletRequest. From the request you can get a handle to the session.

And both request and session offer methods getAttribute() and setAttribute(). So, to pass data from one action to another, set that data as a (request or session) attribute, then read out the attribute in the next action again.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

I don't understand what you're asking. You can pass values as arguments to methods or constructors, and it doesn't matter if those methods or constructors are from other classes than where you're calling them from. If you create a new object, then that object will ofcourse be initialized with default values, or with whatever values the constructor stores in the object.

Can you explain exactly what the problem is with a more detailed and concrete example?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
James Elsey
Ranch Hand

Joined: Dec 21, 2007
Posts: 228

Is it ok for you to post some sample code of what you have? It would help us give you a better answer

When you call Object a = new Object(); you are creating a "new" and "blank" object with nothing set, so you would either have to set all your attributes or just pass the object into another class via a method, maybe something like :

Class A


Class B (someOtherClass)


Kind Regards, James. OCPJP 1.6 || My SCJP / OCJCP Study Notes
Interested in : SCJP, Google App Engine, Stripes, Android;|| My Bite-Size SCJP Study Blog
Matt Kohanek
Village Idiot
Ranch Hand

Joined: Apr 04, 2009
Posts: 483

I did post a similar question in struts forum, but I was also wanting to figure out how to do this within java code only.

My question can be boiled down like this:

After a method in ClassA assigns some values, how do I get one of those values out in a subsequent method call in ClassB. So after ClassA is done, let's say user="user" is stored in UserClass. Now I want to call this value, whatever it may be in ClassB. I cannot do



because that sets all values to null.

I was just wondering if there was something like



that I could use that would bypass instantiating a new Object. So far no luck finding a way, but maybe there just is not one.

My only answer so far has been to allocate some memory space (public interface TempValue{}) and in methodA, assign a temp variable with the value. Then when i want to use the value later in methodB, I have to reference the temp variable still stored in that memory space.

I was just certain there must be an easier way to handle this. It seems like it is a basic thing that I just never learned during my education, but perhaps that is not the case.
James Elsey
Ranch Hand

Joined: Dec 21, 2007
Posts: 228

Hey Matt,

Yeah I think I found your other post.

Maybe I'm not understanding your requirements well, but I would try something like the following (obviously you would change the methods etc)


This is the parent class



This is the "AnotherClass" class



So, what we do, is pass our user object into this other class. We then do something to it, in my case we just change a name on that object, then return it.

What exactly is your business requirements use case?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

I still don't understand what your question is about...

Matt Kohanek wrote:After a method in ClassA assigns some values, ...

Assigns values to what? Local variables in the method, member variables of the current object, or something else?

Matt Kohanek wrote:... how do I get one of those values out in a subsequent method call in ClassB. So after ClassA is done, let's say user="user" is stored in UserClass.

Member variables are normally per object, not per class (unless they are static). So you don't store values in a class, but in an object (which is an instance of a class).

Matt Kohanek wrote:I cannot do



because that sets all values to null.

If you create a new instance of class UserClass like that, then what the values of the member variables of that instance are depends on what the constructor of class UserClass does. Member variables have default values, the default value for reference types is null. If the constructor doesn't initialize the member variable, it will be null.

Matt Kohanek wrote:I was just wondering if there was something like


That's not valid Java and I don't understand what you intend this code to do.

Matt Kohanek wrote:My only answer so far has been to allocate some memory space (public interface TempValue{}) and in methodA, assign a temp variable with the value. Then when i want to use the value later in methodB, I have to reference the temp variable still stored in that memory space.

Well, data has to be stored somewhere and your program has to keep track of it, you can't magically have data appear out of nothing in your program.
Matt Kohanek
Village Idiot
Ranch Hand

Joined: Apr 04, 2009
Posts: 483

James, I think you have answered my question. I will need to do some experimenting to be sure, but I think that is the basic principle in java that I somehow skipped over.

I will update this thread once I have had a chance to try this
James Elsey
Ranch Hand

Joined: Dec 21, 2007
Posts: 228

Yeah no worries, keep us posted (its nice to find a thread I can actually be useful for ;) )
Matt Kohanek
Village Idiot
Ranch Hand

Joined: Apr 04, 2009
Posts: 483

Jesper,

I meant assigning to a variable in an Object (String username = null;), and I mistakenly used the term Class when I should have been saying Object, so I can easily see how confusing this was. Using the correct terms with java has always been a problem for me, I self taught myself most of it and I never bothered to know exactly what certain terms meant, so I often interchange them by mistake.

I know about using the constructor to assign default values, but in my example I should have said all the default values are null. The values are being assigned after some action from a user on a jsp page, such as logging in assigning the username variable and the password variable.

I realize that code you refer to is not valid code, that is why I said "I was just wondering if there was something like that I could use that would bypass instantiating a new Object." I intended for it to show what I was attempting to do, but apparently it just lead to more confusion on what I was trying to say. Lesson learned

Thanks for taking the time to reply, I hope this cleared up some of my mistakes


edit - Let me ask this. When variables within an Object are filled with values (lets say all String values), are those variables reset to default once you move on to methods in a different Object? Or do those variables keep those assigned values until something is done to change them?

Maybe this will also help. In the past, the way I solve this problem is by just piling all my classes within one Object, which I know is horrible, but it was the only way I knew to use assigned variable values from one class within another class. I hope my terms are correct there
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

if you declare a class like this:



Then, somewhere in your code you do this:


Each instance of the class has it's own set of Strings. What you do or changed in class1 will have NO EFFECT on what is in class2...


will print "Fred" twice.

Think of a class as a blueprint for a house. You can use that blueprint to make two houses at different addresses. Each will have their own bedrooms, their own kitchen, etc. Re-painting the bedroom in house1 blue will not have any effect on the bedroom in house2.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Matt Kohanek
Village Idiot
Ranch Hand

Joined: Apr 04, 2009
Posts: 483

No I understand that. Here is the solution I have come across through suggestions from others and some playing around just now.

When the user logs in, within that login java code I added:

where sUserName is that request attribute assigned upon login.

Then when I need to use this value in a different Class, I used

This worked just fine

I was just needing to use a username assigned value across different classes, and I thought there was a simpler way to pass this value from class to class. Is the method I posted above the usual way to do this, or is there actually some other more preferable way? I am thinking I have stumbled across the answer to my question, I just expected some other way of doing this, so it took me a while to realize it.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

Matt, using the ServletContext to store things like the username is not going to work. There is only one ServletContext for the whole web application. If multiple users use your web application at the same time, they will share the ServletContext. If you set the username attribute for one user, and after that for another user, you'll overwrite it for the first user.

In a web application, you can use the session object instead to store per-user data. In your servlet, you get a HttpRequest object passed, on which you can call the getSession() method to get the HttpSession object. Store your data there, instead of in the ServletContext.

The servlet container will take care of creating one HttpSession object per user for you.
Matt Kohanek
Village Idiot
Ranch Hand

Joined: Apr 04, 2009
Posts: 483

Ah that clears up what someone in the struts forum was trying to tell me.

Luckily this is just a class project so only one user at a time will try to log in, but I am going to try and make it usable by multiple people before it is due.

I think the answer to my original question here is it simply depends on the situation.


How about this then: If this were a java app only, working only with JOptionPanes (or whatever may have replaced that by now) for input and output.

A user inputs his name through the JOptionPane, and hits submit, setting the User Class String variable - sName. Now if I want to grab the value of this String variable within another Class, would using the ServletContext be appropriate here, or is there a better way?
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

ServletContexts are found only in web apps, not Swing apps.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

deepika deepi,
Your post was moved to a new topic.
Please post new questions in a new topic.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Passing variables from class to class (SOLVED)