简体   繁体   中英

Changes being made to an object in Java

I have created a Compound class that holds the number of Carbon, Hydrogen, Oxygen, Nitrogen and it's bond count. I have a stack that holds these objects.

Initially the stack will start off at empty and I will pop that. Then I will apply addHydrogen function to it so it's Hydrogen will = 1, Oxygen=0, Nitrogen=0 and Carbon=0.

I then want to take the same object and apply the addCarbon function so that Hydogren will = 0, Oxygen=0, Nitrogren=0 and Carbon=1.

How can I write my program so I can use the same object but not with the changes I made from adding the Hydrogen? I know I could use some if cases initially but I don't think it will work because I will eventually start with a compound that has hydrogen=2, oxygen=2, Nitrogren=0, Carbon=1.

*I didn't include my constructors in the code, they just initialize everything to 0.

class compound {

    int Hydrogen;
    int Carbon;
    int Nitrogen;
    int Oxygen;
    int bond;

    public void addHydrogen(compound comp) {
        Hydrogen++;
    }

    public void addCarbon(compound comp) {
        Carbon++;
    }

}
    public static void main(String[] args) {
        Compound a= new Compound();
        a.addHydrogen(a);
        a.addCarbon(a);
    }

Your question isn't very clear, but one option you might wish to consider would be to make your object immutable - so you could never change the values within a single object, but you could instead make your addCarbon (etc) methods return a new object with appropriate new values in.

(Note that currently you're not using your parameters, which appear to have the wrong case anyway...)

Sample code:

public class Compound {
    private final int hydrogen;
    private final int carbon;
    private final int nitrogen;
    private final int oxygen;

    public Compound(int hydrogen, int carbon, int nitrogen, int oxygen) {
        this.hydrogen = hydrogen;
        this.carbon = hydrogen;
        this.nitrogen = nitrogen;
        this.oxygen = oxygen;
    }

    public int getHydrogen() {
        return hydrogen;
    }

    // ... etc for the other getters

    public Compound plusHydrogen() {
        return new Compound(hydrogen + 1, carbon, nitrogen, oxygen);
    }

    // etc for the other plus calls
}

Note that I've called the methods plusHydrogen etc to make it clear that they're not mutating the existing object, but returning a new one.

Then you can have:

Compound base = new Compound(0, 0, 0, 0);
Compound withHydrogen = base.plusHydrogen();
Compound withCarbon = base.plusCarbon();
// whatever

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