Type casting

P

programming

Hi all, i was just wondering with the below program what effect what
type casting have on the final output. I tried compiling the sample
below, but there were to many bugs in the program to get it to work. I
think that type casting would copy the value "cufflinks for Aus" into
T2, and it would be printed out twice. Can somebody verify this with
me.


public class Thingy
{
public TextField value;

public Object clone()
{
Thingy n;

n=new Thingy();
n.value=this.value;

return n;
}
}


------------------------------------------------------------------------------------------------------------------------------------------------
public class Question
{
Thingy t1,t2;

public static void main(String args[])
{

t1= new Thingy();

t1.value.setText("Cufflinks for Aus");

t2=(Thingy) t1.clone();
t2.value.setText("Bah Humbug!");
}


}
 
D

Daniel Pitts

programming said:
Hi all, i was just wondering with the below program what effect what
type casting have on the final output. I tried compiling the sample
below, but there were to many bugs in the program to get it to work. I
think that type casting would copy the value "cufflinks for Aus" into
T2, and it would be printed out twice. Can somebody verify this with
me.


public class Thingy
{
public TextField value;

public Object clone()
{
Thingy n;

n=new Thingy();
n.value=this.value;

return n;
}
}


------------------------------------------------------------------------------------------------------------------------------------------------
public class Question
{
Thingy t1,t2;

public static void main(String args[])
{

t1= new Thingy();

t1.value.setText("Cufflinks for Aus");

t2=(Thingy) t1.clone();
t2.value.setText("Bah Humbug!");
}


}

Hmm, I think its time for you to get a Java book.
 
L

Lew

Most times one should keep member variables private and use accessor methods
to get at them.
Your intent is to override Object.clone(), correct?

This causes the clone to share a reference to the same TextField as its
progenitor's.
return n;
}
}


------------------------------------------------------------------------------------------------------------------------------------------------
public class Question
{
Thingy t1,t2;

public static void main(String args[])
{

t1= new Thingy();

t1.value.setText("Cufflinks for Aus");

t2=(Thingy) t1.clone();
t2.value.setText("Bah Humbug!");

This replaces the text attribute in the value field that is pointed to by both
t1 and t2.

Not only is the TextField 'value' shared, but it has public access, meaning
that it's subject to change any ol' which where.

- Lew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top