Mam taki kod:
import java.util.*;
public class Test {
private int a;
private String napis;
//konstruktor
public Test(){
this(1,"pusto");
}
//konstruktor nr2 z argumentami
public Test(int a, String n){
this.a = a;
this.napis = n;
{
a=666;
napis="lalala";
}
}
public int getA(){
return this.a;
}
public String getNapis(){
return this.napis;
}
public void setA(int x){
this.a = x;
}
public void setNapis(String n){
this.napis = n;
}
public static void main(String[] args){
Test t1 = new Test();
//t1.setA(333);
//t1.setNapis("Blablabla");
System.out.println("a="+t1.getA()+", napis="+t1.getNapis());
}
}
Otrzymuję wynik:
a=1, napis=lalala
Dlaczego zmienna 'a' nie jest równa 666 ? Napis się zmienił poprzez blok w konstruktorze 2-argumentowym.
Co dziwne, gdy zmienię argument przekazywany w tym konstruktorze z 'a' na 'z' jest ok:
//konstruktor nr2 z argumentami
public Test(int z, String n){
this.a = z;
this.napis = n;
{
a=666;
napis="lalala";
}
}
Wiem, że jak tam zmienie parametr konstruktowa z 'n' na 'napis' to też będzie inaczej, ale nie potrafię tego sobie wytłumaczyć.