简体   繁体   中英

shared values between classes in Java

I have a problem and I need your help. We have two different classes.

class 1:

public class class1 {
    
    private String value = randomValue();
    
    public String randomValue() {
        int x = (1 + (int)(Math.random() * ((100000 - 1) + 1))) + (1 + (int)(Math.random() * ((90 - 1) + 1)));
        return String.valueOf(x);
    }

    public String getValue() {
        return value;
    }
}

class 2:

public class class2 {

    class1 c = new class1();

    public String valueClass2() {
        return c.getValue();
    }
}

The problem is that I want to get the value of X in the first class, so that I can use it in the second class.

Is there a clear way to do this? Thank you

public class class1 {

    private int x;
    
    private String value = randomValue();
    
    public String randomValue() {
        x = (1 + (int)(Math.random() * ((100000 - 1) + 1))) + (1 + (int)(Math.random() * ((90 - 1) + 1)));
        return String.valueOf(x);
    }

    public String getValue() {
        return value;
    }
    
    public int getX() {
        return x;
    }
}

Differentiate between classes and the instances of a class. If you create a new instance of class1 in an instance of class2 , you cannot access the data of another, previously created instance of class1 . Declare a class2 constructor that takes an instance of class1 . You can then access a previously created instance of class1 and call getValue() as in your example.

An example:

public class class2 {
    private class1 c;

    // Constructor that accepts a reference to your instance of class1
    public class2(class1 class1Instance) {
        // TODO: prevent that (class1Instance == NULL)
        
        this.c = class1Instance;
    }

    public string valueClass2() {
        return c.getValue();
    }
}

To better distinguish between a class and an instance of a class, it is recommended that class names always begin with an uppercase letter. The variable name of the instance always starts with a lower case letter.

eg

Class1 class1Instance = new Class1();
// do something with class1Instance ...
Class2 class2Instance = new Class2(class1Instance);

I hope that I recognized your problem correctly and that my hints are a solution for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM