简体   繁体   中英

How to communicate atributes between classes

I have two classes, Window and Register, I catch a String in Window then i need to use in Register. Here is a piece of my code:

public class Window extends JFrame{
private String city;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public Window() {
    Interface();
}

public void Interface(){

    botonContinuar = new JButton("Next");
    botonContinuar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //This get the value from my list...
            setCity((String) listaCity.getSelectedValue());

            Register open=new Register();

        }
    });
    botonContinuar.setBounds(164, 203, 89, 42);
    panel.add(botonContinuar);

}

public class Register extends Window{

public Register() {
    Window window=new Window();

    System.out.println(window.getCity());

}

Output is :null:, when i was expecting the city catched from the list in Window. I'm new with Java, but I suppose the problem is that im creating a new Window objetc then all my atributes got initialized, but I cant figure out how to avoid this.

Thanks in advance

When you will use this constructor, the city property will be initialized and you will see your output. Witoout it, the city remains null .

Window window=new Window("New York");

System.out.println(window.getCity());

Another option is to use public void setCity(String city) method, like:

Window window=new Window();
window.setCity("New York");
System.out.println(window.getCity());

Couple of things:

  • Unless and until you set city by default city variable would be null by default.
  • You call set city only when you press button, which you never did.

If you need default value, i would suggest you initialize it like:

private String city = "defaultValue"; //or modify constructor to pass city value when object initializes.

I see two problems

  1. You do not set the city attribute in Window's constructor. As it stands Register would have to call Window's actionPerformed action for the city to be set.
  2. In Window's Interface method a new Register is instantiated. This might be a problem because if Register requires Window's Inteface method to be called, but Interface requires new Register to be called then this may lead to a StackOverflow exception or circular dependency.

Here are some suggestions:

  1. Either Register calls new Window() , or Window calls new Register() but not both.
  2. Consider passing the city to Register in the constructor.

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