简体   繁体   中英

What happens when you say Object someObject = otherSameObject;

I'm making an application in Java using a JTabbedFrame. Each tab is created by a separate class extending JFrame. I would like to save each tab's state by saving the object to a file on window close and read them back from the file when the tabs are created. I know when you serialize an object all the instance variables are saved, but what happens to the constructor? When I say for example in the class that builds the tab frame:

public class Jtab{
    private ClassThatExtendsJFrame tab;

    public Jtab(ClassThatExtendsJFrame tab){  

         this.tab = tab; // what happens here? Is the constructor called?
         JTabbedPane tabs = new JTabbedPane();
         tabs.addTab("name", icon, this.tab, "tooltip");
    }

}    

All of the code that lays out the JFrame is currently in the constructor. All of the JLabels and elements in the the layout are properties of the class which I assign in the constructor. So I see there are two options that might happen: The constructor is called and all the variables are reset, or the constructor is not called and and my layout is not created. What's the best way to accomplish what I am looking to do?

You can never say object = object since the left side of an assignment expression cannot be an "object". Rather it is a reference variable of some type. So instead you can only do variable gets assigned object reference. Or variable gets compared to another variable reference.

you are saying

this.tab = tab;

they are two different references.

this.tab refers to the field of the class

tab refers to the parameter of the constructor.

thus you are assigning the reference referred by the parameter to the field.

In the constructor, you are assigning a local field to the value passed into the constructor where the field and the local variable have the same name -

public Jtab(ClassThatExtendsJFrame tab){  
     this.tab = tab; // assign tab from the argument to this instance's field

Could also be written as

public Jtab(ClassThatExtendsJFrame that{  
     tab = that; // <-- this.tab

Again, the this was to overcome the name collision.

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