Una dudilla
Publicado por Edurne (1 intervención) el 10/10/2005 13:47:29
Estoy aprendiendo a programar java y no entiendo este ejemplo, la salida al ejecutarlo es:
p = NewPoint[123456789,2147483647], entiendo todo el proceso pero no entiendo en que momento thawed se convierte en una cadena , porque se ejecuta toString sin llamarla, cuando lo logico sería poner en el System.out.println("p = " +thawed.toString()); y no thawed solo. Muchas gracias
El código es este
-----------------------
interface Packable{
byte[] pack();
void unpack(byte raw[]);
}
class Point{
int x, y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
class NewPoint extends Point implements Packable{
NewPoint(int x, int y){
super(x, y);
}
NewPoint(){
this(0, 0);
}
private byte p(int t, int n){
return (byte)((t>>n) & 0xff);
}
public byte pack()[]{
byte ret[]=new byte[8];
ret[0]= p(x, 24);
ret[1]= p(x, 16);
ret[2]= p(x, 8);
ret[3]= p(x, 0);
ret[4]= p(y, 24);
ret[5]= p(y, 16);
ret[6]= p(y, 8);
ret[7]= p(y, 0);
return ret;
}
private int u(byte b, int n){
return (b & 0xff)<<n;
}
public void unpack(byte raw[]){
x=u(raw[0], 24) | u(raw[1], 16) | u(raw[2], 8) | u(raw[3], 0);
y=u(raw[4], 24) | u(raw[5], 16) | u(raw[6], 8) | u(raw[7], 0);
}
public String toString(){
return "NewPoint[" + x + "," + y + "]";
}
}
class PointPack{
public static void main (String args[]){
Packable p= new NewPoint(123456789, 2147483647);
byte packed[] =p.pack();
NewPoint thawed= new NewPoint();
thawed.unpack(packed);
System.out.println("p = " +thawed);
}
}
p = NewPoint[123456789,2147483647], entiendo todo el proceso pero no entiendo en que momento thawed se convierte en una cadena , porque se ejecuta toString sin llamarla, cuando lo logico sería poner en el System.out.println("p = " +thawed.toString()); y no thawed solo. Muchas gracias
El código es este
-----------------------
interface Packable{
byte[] pack();
void unpack(byte raw[]);
}
class Point{
int x, y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
class NewPoint extends Point implements Packable{
NewPoint(int x, int y){
super(x, y);
}
NewPoint(){
this(0, 0);
}
private byte p(int t, int n){
return (byte)((t>>n) & 0xff);
}
public byte pack()[]{
byte ret[]=new byte[8];
ret[0]= p(x, 24);
ret[1]= p(x, 16);
ret[2]= p(x, 8);
ret[3]= p(x, 0);
ret[4]= p(y, 24);
ret[5]= p(y, 16);
ret[6]= p(y, 8);
ret[7]= p(y, 0);
return ret;
}
private int u(byte b, int n){
return (b & 0xff)<<n;
}
public void unpack(byte raw[]){
x=u(raw[0], 24) | u(raw[1], 16) | u(raw[2], 8) | u(raw[3], 0);
y=u(raw[4], 24) | u(raw[5], 16) | u(raw[6], 8) | u(raw[7], 0);
}
public String toString(){
return "NewPoint[" + x + "," + y + "]";
}
}
class PointPack{
public static void main (String args[]){
Packable p= new NewPoint(123456789, 2147483647);
byte packed[] =p.pack();
NewPoint thawed= new NewPoint();
thawed.unpack(packed);
System.out.println("p = " +thawed);
}
}
Valora esta pregunta


0