• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Passing variables from class to class (SOLVED)

 
Village Idiot
Posts: 484
jQuery Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 231
Android IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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)
 
Matt Kohanek
Village Idiot
Posts: 484
jQuery Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 231
Android IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 484
jQuery Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 231
Android IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah no worries, keep us posted (its nice to find a thread I can actually be useful for ;) )
 
Matt Kohanek
Village Idiot
Posts: 484
jQuery Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
lowercase baba
Posts: 13091
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Matt Kohanek
Village Idiot
Posts: 484
jQuery Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 484
jQuery Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ServletContexts are found only in web apps, not Swing apps.
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
deepika deepi,
Your post was moved to a new topic.
Please post new questions in a new topic.
reply
    Bookmark Topic Watch Topic
  • New Topic