I've been looking for the answer to this problem all day.
I have a value class that holds a variety of values as long as the program is running.
I create a new Value object in class A, and store an int value.
Class A also has a printMoney() method.
public class A {
Value value = new Value();
value.setMoney(100);
public void printMoney {
System.out.println(value.getMoney);
}
In class B, I want to be able to call printMoney() from class A, so logically I do the following:
public class B {
A a = new A();
a.printMoney();
}
This does, however, return '0' as a value instead of '100'.
I understand that by creating an A object, I automatically create a new value object, which has its default money value. So, basically my question is; how do I solve this?
Make the object static. static Value value = new Value();
static variables are shared across all the objects
So the change made in static variable will be reflected for all the objects of class.
if you want to get that value in A you have to assign the value in A construtor, like
public class A {
Value value = new Value();
public A() {
this.value.setMoney(100);
}
otherwise, you can make the value static
you should receive the instance that creates the object B and save it then you would be able to call it
like so:
public class A {
B b = new B(this);
}
public class B {
A a;
public B(A a) {
this.a = a;
}
private someMethod () {
a.printMoney();
}
}
Related
This is a mostly theoretical example, but how do I refer to the instance variable "a" in the constructor, but not the current object variable "this.a", after a local variable "a" has been declared?
public class Foobar {
public int a = 0;
public Foobar(int a) {
this.a = a;
}
public Foobar(int b, int c) {
a = b * c;
int a = c; //after this point, is there any way of refer to the instance variable a but not a in the current object (i.e. this.a)?
}
public int getA() {
return this.a;
}
public static void main(String[] args) {
Foobar foo = new Foobar(3);
Foobar bar = new Foobar(3, 1);
System.out.println(foo.getA());
System.out.println(bar.getA());
}
}
There is no class variable in your code.
If you want a class variable, use static int a. Of course, you won't be able to refer to a class variable using this.a: that only works with instance variables.
And, of course, you can't have a class variable and an instance variable with the same name.
If you override the class variable with a local variable, (bad idea - don't do that - most IDEs will warn you) then can refer to the class variable with Foobar.a
I am facing problems while trying to implement 2 linked lists in my Java code.
If I declare my "head" variables in main and pass them to any function, they could not be modified by that function as the referencing variable would be local to that function.
But if I make them class variables, the called function could not know which of the 2 "head" variables I am referring to.
This problem could be easily solved in C language by passing double pointers in functions so that the local variable can modify the passed variable but how to solve this problem in Java? Thanks.
Pointers aren’t used in Java
Defines the attribute at the class level and don't use it in the signature of your methods, or return the value of your function to the original variable.
public class MyClass{
private string value;
public myFunction(){
value = toto; // this will change the value of the attribute directly
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.myFunction(); // The new value is saved at the class level
}
}
or
public class MyClass{
public String myFunction(String value){
value = "toto";
return value; // The value modified is return back to the caller
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
String myValue = myClass.myFunction(myvalue); // The new value is saved
}
}
If I have a constructor
public class Sample {
public static StackOverflowQuestion puzzled;
public static void main(String[] args) {
puzzled = new StackOverflowQuestion(4);
}
}
and inside the main method of a program i have
public class StackOverflowQuestion {
public StackOverflowQuestion(){
//does code
}
public StackOverflowQuestion(int a){
this();
}
}
Is this creating an instance of StackOverflowQuestion via constructor2 and then creating another instance of StackOverflowQuestion via constructor 1 and therefore i now have two instances of StackOverflowQuestion directly inside each other?
Or does constructor2 in this case kind of laterally adjust and then instead create an instance of StackOverflowQuestion via constructor1 ?
I think you mean:
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
And call it like:
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
This will only create one object, because new is executed only once. The call this() will execute the code in the other constructor without creating a new object. The code in that constructor is able to modify the currently created instance.
It only creates one instance. One use case of it is to give default values for constructor parameters:
public class StackOverflowQuestion
{
public StackOverflowQuestion(int a) {
/* initialize something using a */
}
public StackOverflowQuestion() {
this(10); // Default: a = 10
}
}
this() is not the same as new StackOverflowQuestion()
this(5) is not the same as new StackOverflowQuestion(5)
this() and this(5) calls another constructor in the same class.
Therefore in this example:
public class StackOverflowQuestion
{
private int x;
private int y;
private int a;
public StackOverflowQuestion(){
this.x = 1;
this.y = 2;
}
public StackOverflowQuestion(int a){
this();
this.a = a;
}
}
The call to this() will just initialize the object and not create a new instance. Remember new StackOverflowQuestion(5) has been called already invoking the constructor which actually creates a new instance of the StackOverflowQuestion object
A constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Read through Creation of New Class Instance - JLS. Now what does this mean :
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
A new object of StackOverflowQuestion is created by the new operator, just before a reference to the newly created object is returned as the result and assigned to the StackOverflowQuestion puzzled reference variable , the constructor StackOverflowQuestion(int a) makes a call to this() i.e. public StackOverflowQuestion(), code(if any) inside the default constructor runs and the control comes back to `StackOverflowQuestion(int a), the remaining code(if any) inside that is processed to initialize the new object.
The instance of a class is created at the moment you use the "new" operator. It is perfectly possible to create a class without constructors, because in that case, by default, the constructor with no parameters is available.
The "this" keyword just points to THIS specific object, so calling "this()" means "call my own constructor function, the one without parameters and execute what's inside"
if i want to call multiple methods of a one class from another class can i call them by using only 'new classname()' without catching it in class reference?
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new pqr().a=5;
new pqr().b=10;
new pqr().display();
}
}
class pqr
{
int a,b;
public void display()
{
System.out.println(a+" "+b);
}
}
This creates three new objects. Not just one.
new pqr().a=5;
new pqr().b=10;
new pqr().display();
One object with a = 5 and another with b = 10.
Remember you are not working with one object.
Whenever you use new keyword. JVM creates a new object.
if i want to call multiple methods of a one class from another class can i call them by using only 'new classname()' without catching it in class reference?
It's not clear what you mean by "catching it" but you are using a reference... you're just not assigning it to a variable.
In your example, you're creating three different objects - the calculation on your final line just prints 0, because you've only set a and b in other objects. If you want to use a single object for multiple operations, you'll either need to store the reference in a variable, or those operations will have to return "this", allowing you to chain method calls together:
class Sample {
private int a,b;
public void display() {
System.out.println(a+" "+b);
}
public Sample setA(int a) {
this.a = a;
return this;
}
public Sample setB(int b) {
this.b = b;
return this;
}
}
...
new Sample().setA(5).setB(10).display();
This sort of chaining for setters is common in the builder pattern.
You can use the Builder pattern if you want something like that:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();
The builder pattern is one possibility. The another one is to have static properties so all object will share it's values.
static int a,b;
Lets say I have 3 Classes: A, Data, and B
I pass a variable from class A which sets that passed variable to a private variable in class Data.
Then in class B, I want to call that specific variable which has been changed.
So I do
Data data = new Data();
data.getVariable();
It will then return null, since in class Data I initialize variables to nothing (ex: int v;), and I think that class B is initializing a brand new class and resetting the values to default, but I don't know how to fix this.
I know that the variable is setting properly because in class A if I do data.getVariable() it will print the variable that was set.
Class A:
Data data = new Data();
int d = 1;
data.setVariable(d);
Class Data:
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
Class B:
Data data = new Data();
private int v;
v = data.getVariable();
System.out.println(v);
This will print out 0 instead of the actual value
When you instantiate a Data object in class A, and instantiate another Data object in class B, they are two different instances of the Data class. They both instantiate d to 0 by default. You then call setVariable on the instance in class A and pass it the value of 1; but the instance in class B remains in 0. In order to change the value of the instance in class B, you would need to call setVariable on the instance in class B.
What it seems like you're looking for is a static member. Static members are the same across all instances of the same class. Just put the static keyword before the method(s) or field(s) that you want to use it. Static members and fields are typically accessed using the name of the class in which they are declared (i.e. MyClass.doMethod()). For example:
Class Data (updated):
private static int b;
public static void setVariable(int s)
{
b = s;
}
public static int getVariable()
{
return b;
}
Class A:
Data.setVariable(d);
Class B:
v = Data.getVariable();
System.out.println(v);
Editing - my first suggestion was to use static for variable b, and the author changed his question adding that suggestion.
It fixes what you are trying to do. I write the example in code that compiles:
public class Demo {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.doWhatever();
b.doSomethingElse();
}
}
class Data {
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
}
class A {
public void doWhatever() {
Data data = new Data();
int d = 1;
data.setVariable(d);
}
}
class B {
Data data = new Data();
private int v;
public void doSomethingElse() {
v = data.getVariable();
System.out.println(v);
}
}