May I do data type conversion within getter/setter?

R

Raoul Markus

Hi,

I had to change the type of in private variable (from java.util.Date to
java.sql.Date). May I do type conversions within the getters and setters to
let the outside interface stay untouched?
i.e.

private java.sql.Date mDate;

public java.util.Date getDate() {
return new java.util.Date(mDate.getTime());
}
 
J

Juha Laiho

Raoul Markus said:
I had to change the type of in private variable (from java.util.Date to
java.sql.Date). May I do type conversions within the getters and setters to
let the outside interface stay untouched?

Yep; that (being able to modify the class internals without needing to
modify anything outside the class) is one of the reasons you have getters
and setters instead of just providing public access to the variables.
 
D

David Zimmerman

Raoul said:
Hi,

I had to change the type of in private variable (from java.util.Date to
java.sql.Date). May I do type conversions within the getters and setters to
let the outside interface stay untouched?
i.e.

private java.sql.Date mDate;

public java.util.Date getDate() {
return new java.util.Date(mDate.getTime());
}
That's one of the best reasons to use getters/setters. When the
internal data needs to change but you don't want the external API to change.
 
R

Roedy Green

I had to change the type of in private variable (from java.util.Date to
java.sql.Date). May I do type conversions within the getters and setters to
let the outside interface stay untouched?

yes. Further there is nothing to do.

you can write:

private java.sql.Date d;

public java.util.Date getDate()
{
return d;
}

Since java.sql.Date is a subclass of java.util.Date.

Most people would not even mind if you wrote:

public java.sql.Date getDate()
{
return d;
}

Since they can use the result as a java.util.Date without conversion.
 

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

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top