简体   繁体   中英

Why does its value change?

I have that following java code:

public class HelloWorld
{
    static Baumhaus bauHaus(int hoehe, int breite)
    {
        Baumhaus b = new Baumhaus();
        b.hoehe = hoehe;
        b.breite = breite;
        return b;
    }

    static Baumhaus machBreiter(Baumhaus b)
    {
        Baumhaus bb = new Baumhaus();
        bb.hoehe = b.hoehe;
        bb.breite = b.breite + 1;
        return bb;
    }

    static Baumhaus machHoeher(Baumhaus b)
    {
        b.hoehe++;
        return b;
    }

    public static void main(String[] args)
    {
        Baumhaus b = bauHaus(2, 3);
        Baumhaus c = machBreiter(b);
        c.nachbar = b;
        Baumhaus d = machHoeher(b);
        d.nachbar = b;
        ++c.hoehe;
        Baumhaus e = machHoeher(b);
        e.nachbar = c;
        e.breite = b.breite - 1; // WHY DOES b.breite GETS DECREASED BY 1 ???
        c.hoehe++;
        c.breite -= 2;
        boolean bUndCBenachbart = (b.nachbar == c || c.nachbar == b);
    }
}

class Baumhaus
{
    public int hoehe;
    public int breite;
    public Baumhaus nachbar;
    public int nummer = ++naechsteNummer;
    static int naechsteNummer = 0;
}

See the commented line ( e.breite = b.breite - 1; ) I can't understand, why the value of the variable b.breite gets changed. I'm reading a documentation about Object Oriented Programming (Java) but I am still scratching my head. Please help me

Note: I don't know how to describe my problem to google, so I couldn't find any solutions about my question. I'm sorry if duplicate

Thanks in advance :)

Because e == b .

e is defined as Baumhaus e = machHoeher(b); and

static Baumhaus machHoeher(Baumhaus b)
{
    b.hoehe++;
    return b;
}

in java assigning object will not create distinct copies of them.

the method :

static Baumhaus machHoeher(Baumhaus b) {
    b.hoehe++;
    return b;
}

returns the the same object it recives as a parameter, so in the code line

Baumhaus e = machHoeher(b);

e object is a reference of b , decreasing e will also decrease b

The issue is that you are returning the same object in the machHoeher function. the function is returning the same object that was passed in. So you have two variables (e and b) pointing to the same object in memory.

In machBreiter, you are creating a new object, incrementing the breite, then returning the new object.

You should do the same in machHoeher:

  • Create New object
  • Inrement the hoehe
  • return the new object.

This will make sure that when you do e.breite = b.breite - 1, e and b are separate objects and b.breite doesn't get changed.

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