0

For example let's say we have the property called Customer that returns a value of name

String name; <== Global Variable

public String getName()
{
   return name;
}

public String setName(holdingName)
{
   name=holdingName;
}

and a constructor called Match

public FullName(String realName) 
{
    holdingName = realName;
}

Can I do what I have done up there? I know it does not work, but is there any way to make it work?
Please let me know if you need further information to get this question answered..

Thank you

4
Contributors
7
Replies
28
Views
4 Years
Discussion Span
Last Post by stultuske
0

your question makes no sense. first of all, there are no global variables in Java. I assume you are talking about instance variables.
also: your code doesn't make sense.
In your constructor, you assign the value name to a non-existing variable holdingName. why? because that's the name of the parameter you use in setName?
you don't need the setter to set the value in a constructor. just put 'this.name = name;' and you're set.

what exactly is it that you mean, if this doesn't answer your question?

-1

It is hard to understand what you mean, but I think I have it.
when you do this:

public String setName(holdingName)
{
   name=holdingName;
}

you want to set a global varible to a new value. Just use this like so

public String setName(String holdingName) {
    this.name = holdingName;
}
0

But would I be able to use it in the constructor? Because it won't allow me to do this.

1

m4trixSh4d0w: try and keep your answers logic -> there are NO global variables in Java.
xHellghostx: read my previous post. yes you can, but there is no reason to do so.

the variable name 'holdingName' is only known locally within your set-method, so that you can't use in your constructor.

next to the correction m4trixSh4d0w pointed out, you can do either this:

public FullName(String realName) 
{
    this.name = realName; // NOT HOLDINGNAME, SINCE THIS VARIABLE DOESN'T EXIST IN THIS SCOPE
}

or you could use:

public FullName(String realName) 
{
    setName(realName);
}

personally, I would go for the first option.

Votes + Comments
Yeah I figured it out last night.. This is the correct way to do it.. Thank you.
1

when you said: "Global" you meant: instance variable.
when you say "local to any point in the class", you are saying two very different things: local and any point in the class.

there are two kind of variables which are available "everywhere" in the class, being an instance variable and a static variable, but they 're not global variables, nor are they "local". a local variable is a variable declared within a method (or even within a loop) and is only known within that method (loop, ... )

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.