how do i extract a string from a comparable object?

hey all,

if i have the following code:

Comparable name = new Client("", "Molly");

String getName;

how is it possible to extract "Molly" from Comparable name and assign it to String getName?

when i print out name i get

System.out.println(name);

Molly, ,

thanx heather

Message was edited by:

heatherGirl

[369 byte] By [heatherGirla] at [2007-11-27 5:37:40]
# 1

You'd have to cast it to a Client.

Client client = (Client)name;

Can I ask why you're declaring it as a Comparable in the first place, rather than as a Client? If Client implements comparable, you can use it wherever a Comparable is required--it needn't be declared as Comparable.

jverda at 2007-7-12 15:10:13 > top of Java-index,Java Essentials,Java Programming...
# 2

simple answer: No, its not possible since Comparable has no method for it

a bit less simpler answer:

if you know (more or less) that it is a Client you can do something like that

if (name instanceof Client) {

Client tmp = (Client) name;

getName = tmp.getName(); // assuming Client has a getName method

}

a bit more complex:

define a ComparableWithName interface, use that instead of just Comparable and let Client implement this one.

interface ComparableWithName extends Comparable {

public String getName();

}

--

ComparableWithName name = new Client("", "Molly");

String getName = name.getName();

S_i_m_ua at 2007-7-12 15:10:13 > top of Java-index,Java Essentials,Java Programming...
# 3
thanx all ive managed to get it working, yes client has a getName method, i just was not sure how to go about retrieving the name but i casted it and it works now thankyou so much heather
heatherGirla at 2007-7-12 15:10:13 > top of Java-index,Java Essentials,Java Programming...