Co się stanie, gdy obiekt zostanie przypisany do innego obiektu
public class DrumKitTestDrive {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Echo e1 = new Echo();
Echo e2 = new Echo();
// **e2 = e1;**
int x=0;
while( x < 4 ){
e1.hello();
e1.count = e1.count + 1;
if(x==3){
e2.count = e2.count + 1;
}
if(x>0){
e2.count = e2.count + e1.count;
}
x = x + 1;
}
System.out.print(e2.count);
}
}
class Echo {
int count = 0;
void hello(){
System.out.println("Hellooooo....");
}
}
Wyjściem tego kodu będzie:
Hellooooo....
Hellooooo....
Hellooooo....
Hellooooo....
10
Ale jeśli usunę komentarze z// e2= e1;
kiedy uruchomię kod, system wydrukuje24 zamiast10. Nie rozumiem dlaczego tak jest?
Rozumiem, że system po prostu skopiuje wartoście1
przykłade2
instancja. A jeśli system to zrobi, wynik pozostanie taki sam, ponieważ oba obiekty należą do tej samej klasy.