How to access field whenever its name is same with local variable? - java

I have a field and a local variable with same name. How to access the field?
Code:
String s = "Global";
private void mx()
{
String s = "Local";
lblB.setText(s); // i want global
}
In c++ use :: operator like following:
::s
Is were :: operator in Java?

That's not a global variable - it's an instance variable. Just use this:
String s = "Local";
lblB.setText(this.s);
(See JLS section 15.8.3 for the meaning of this.)
For static variables (which are what people normally mean when they talk about global variables), you'd use the class name to qualify the variable name:
String s = "Local";
lblB.setText(ClassDeclaringTheVariable.s);
In most cases I prefer not to have a local variable with the same name as an instance or static variable, but the notable exception to this is with constructors and setters, both of which often make sense to have parameters with the same name as instance variables:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

You can use "this" keyword to do this.
Example:
public class Test {
private String s = "GLOBAL";
public Test() {
String s = "LOCAL";
//System.out.println(this.s);
//=> OR:
System.out.println(s);
}
public static void main(String[] args) throws IOException {
new Test();
}
}

Using this keyword you can use the global one but inside the same class. Or simply you can declare global variable static and access the same using classname.variable name.

Yes you can also use
class _ name.Globalvariable_name
Class simple
{
static int i;
public static void main(string args[])
{
int i=10;
System.out.println("Local Variable I =" +i) ;
system.out.println("Global variable I =" +Simple.i)
}
}

Related

Why is my JTextField not saving the input properly? [duplicate]

I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.
Here is my custom file class:
public class MyFile {
private static String path;
private static String name;
private static final String FILE_SEPARATOR = "/";
public MyFile(String path) {
System.out.println(path);
this.path = "";
this.name = "";
this.path = /*FILE_SEPARATOR*/path;
String[] dirs = path.split(FILE_SEPARATOR);
this.name = dirs[dirs.length - 1];
}
public static String getPath() {
return path;
}
public static String getName() {
return name;
}
public String toString() {
return "Path: " + path + ", Name: " + name;
}
}
Here I am using the variables:
MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
The output is the following: http://imgur.com/a/Nu3N6
In MyFile class, you declare these fields as static fields :
private static String path;
private static String name;
So you can assign to them a single value as a static field is shared among all instances of the class.
You should rather declare these fields as instance fields to have distinct values for each MyFile instance :
private String path;
private String name;
First you want to know about static keyword:
Attributes and methods(member of a class) can be defined as static.
static members do not belongs to an individual object.
static members are common to all the instances(objects of the same class).
static members are stores in static memory(a common memory location which can by everybody).
Becauseof two member variables are static. Each objects share the values of these two variables(values are common for every objects).
private static String path;
private static String name;
Remove the static in both variables. Then each and every object will hold a individual values for these variables.
When Defining an Entity class the class variable show be private period. Unless you want to access these variable statically, as in without having to instantiate the class or using getters and setter. If you use getters and setters as you have done above, and clearly made an instance of the class you want use ensure you don't use static access modifiers for the class variables.
The modified code is-as below.
package StackOverflowProblemSets;
/**
* Created by HACKER on 05/06/2017.
* Two different variables getting same value
*/
public class MyFile {
private String path;
private String name;
private static final String FILE_SEPARATOR = "/";
public MyFile(String path) {
System.out.println(path);
this.path = "";
this.name = "";
this.path = /*FILE_SEPARATOR*/path;
String[] dirs = path.split(FILE_SEPARATOR);
this.name = dirs[dirs.length - 1];
}
public String getPath() {
return path;
}
public String getName() {
return name;
}
public String toString() {
return "Path: " + path + ", Name: " + name;
}
public static void main(String[] args) {
MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
}
}
You need to know about static and local variables.
Static variables of a class are such variables which are common to all instances of that class and are shared by all of the instances. E.g. if I have a class:
public static class myClass{
public static int staticVar;
//Constructor
public myClass(){
staticVar = 0;
}
}
and then I have the following code in a main method of another class:
public static void main(String args[]){
myClass c1, c2;
c1 = new myClass();
c2 = new myClass();
c1.staticVar = 4;
c2.staticVar = 8;
System.out.println(c1.staticVar + " " + c2.staticVar);
}
then my output will be:
8 8
This is because the variable staticVar is shared by both c1 and c2. First when the statement c1.staticVar = 4 is executed, the value of staticVar for both c1 and c2 is 4. Then the statement c2.staticVar = 8 is executed to change the value of staticVar of both classes to 8.
So in your problem, you have to make your name and path variables non-static to give each of your myFile instances a different value of the variables.
I hope this helps.
You problem is second file path is overlap of first file path. So, check this code:
MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(new MyFile("res\\model.dae"));
System.out.println(new MyFile("res\\diffuse.png"));

How to override class variable value

This is sample reference example, for what I am looking Solution
Reference Example:
Here demoName is global variable
Somehow I need to define that variable on Class level which is : String demo = demoName;
Now it needs to override variable value with local variable, when it call from local method.
void test(String name) {
demoName = name;
System.out.println("Local Value:" + demoName);
System.out.println("Global Value:" + demo);
}
Here demoName becoming override with parameter value, But when +demo is taking class level value which is XYZ, I want it to be abc.
class demo1 {
public static String demoName = "xyz";
}
public class demos extends demo1 {
String demo = demoName;
void test(String name) {
demoName = name;
System.out.println("Local Value:" + demoName);
System.out.println("Global Value:" + demo);
}
#Test
public void testtest() {
test("abc");
}
}
I want both value to be "abc" .
Because demoName is public, you can reassign it from anywhere using Demo.demoName = "abc";, no need for a subClass at all.
However, using a public static variable and reassignating is awful. If you just want to override it at instance level in a subclass, you should use an accessor and override the accessor :
public static class Demo {
public static String demoName = "xyz";
public String getDemoName() {
return demoName;
}
}
public static class Demos extends Demo {
private String demoNameOverride;
#Override
public String getDemoName() {
return demoNameOverride;
}
}
String is Immutable in java
Note: when two String variables are referencing to the same object, if one variable changes its object at any stage , it only changes that variable Object not the other variable Objects.
String demo = demoName;
at this line of code both variables are referencing to the same object xyz
which means demo and demoName have xyz. the reason why it is not changing its object after
#Test
public void testtest() {
test("abc");
}
because String is immutable in Java. please refer Why is String immutable in Java?
https://www.programcreek.com/2013/04/why-string-is-immutable-in-java/
ex:
static String a="Helloworld";
static String b=a;
public static void main(String[] args) {
System.out.println(a);
System.out.println(b);
a="World";
System.out.println(a);
System.out.println(b);
}
output:
Helloworld
Helloworld
World
Helloworld
this is how your programme logic flows now and b is referencing to its previous Object Only.after you change the String Value and again the reference has to be done.The below example will give you the idea.
public class Demo1 {
public static String demoName = "xyz";
}
class Demo extends Demo1 {
static String demo = demoName;
public void test(String variableName) {
//initially i am calling both varaibles which you assign
System.out.println(demoName);
System.out.println(demo);
// i am assigning the "abc" to demoName and calling both varaibales
demoName = variableName;
System.out.println(demoName);
System.out.println(demo);
// Now i am assigning the "abc" to demo and calling both varaibales
this.demo = variableName;
System.out.println(demoName);
System.out.println(demo);
}
public static void main(String[] args) {
Demo dem = new Demo();
dem.test("abc");
}
}
The Output is :
xyz
xyz
abc
xyz
abc
abc

How to pass a string from one method to another method in Java

I declared string:
private String name;
1st method:
private void showJSON(String response){
name = collegeData.getString(Config.KEY_NAME);
}
I want to use the value of name in this method:
private void setRealmData() {}
Your question is a bit unclear, but there are two distinct cases of how to implement this:
A. The name variable is an instance variable:
public class myClass{
private String name;
private void showJSON(String response){
// name = collegeData.getString(Config.KEY_NAME); - this was your code
this.name = collegeData.getString(Config.KEY_NAME); // Set the 'name' variable to the value you want for this instance
setRealmData(); // No argument passed, provided that 'name' is an instance variable
}
private void setRealmData(){
System.out.println(this.name); // Sample code
}
}
B. The name variable is a local variable:
public class myClass{
private void showJSON(String response){
String name;
// name = collegeData.getString(Config.KEY_NAME); - this was your code
name = collegeData.getString(Config.KEY_NAME); // Set the 'name' variable to the value you want for the method
setRealmData(name); // Single argument passed, provided that 'name' is a local variable
}
private void setRealmData(string name){
System.out.println(name); // Sample code
}
}
Note that the myClass class is a dummy class I used to show the scope of the variables and methods, adjust accordingly.

A parameters' variable as parameter

I have an Object Human:
public class Human {
String name;
public Human(String name){
this.name = name;
}
}
In my main Class I have an instance of this human "John".
With a function called getVarOfObject() I want to get John's name:
public class Example {
public static Object getVarOfObject(Object obj, Object var){
return obj.var;
}
public static void main(String[] args) {
Human john = new Human("John");
String johnsName = getVarOfObject(john, name);
}
}
I know you could just type john.name but in my case I need to have a function which can do this.
You can use this code
Field field = <Your object>.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (String) field.get(object);
You can't do this except reflectively.
Please note that this wizardry can lead to errors, subtle issues, exceptions, performance losses, asphyxiation, drowning, death, paralysis, or fire.
Object obj is the object, and String field is the name of the field.
Class clazz=Human.getClass(); //or for class-independence use `obj.getClass()`.
Field fd=clazz.getField(name);
fd.get(obj);
Why don't you use accessor methods (getters and setters)?
In Human:
public String getName() {
return name;
}
and in your main method:
Human john = new Human("John");
String johnsName = john.getName();

Java - Using Accessor and Mutator methods

I am working on a homework assignment. I am confused on how it should be done.
The question is:
Create a class called IDCard that contains a person's name, ID number,
and the name of a file containing the person's photogrpah. Write
accessor and mutator methods for each of these fields. Add the
following two overloaded constructors to the class:
public IDCard() public IDCard(String n, int ID, String filename)
Test your program by creating different ojbects using these two
constructors and printing out their values on the console using the
accessor and mutator methods.
I have re-written this so far:
public class IDCard {
String Name, FileName;
int ID;
public static void main(String[] args) {
}
public IDCard()
{
this.Name = getName();
this.FileName = getFileName();
this.ID = getID();
}
public IDCard(String n, int ID, String filename)
{
}
public String getName()
{
return "Jack Smith";
}
public String getFileName()
{
return "Jack.jpg";
}
public int getID()
{
return 555;
}
}
Let's go over the basics:
"Accessor" and "Mutator" are just fancy names fot a getter and a setter.
A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless.
B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.
If you use the static keyword then those variables are common across every instance of IDCard.
A couple of things to bear in mind:
don't add useless comments - they add code clutter and nothing else.
conform to naming conventions, use lower case of variable names - name not Name.

Categories

Resources