Showing posts with label Using references in java. Show all posts
Showing posts with label Using references in java. Show all posts

Monday, December 2

Coding Practice to avoid error while using Object references






Let's understand this by example


import java.util.Date;

import java.util.Date;

public class Refree {

public static void main(String args[]) {

Date date = new Date();
Dater coach = new Dater(date);
System.out.println(coach.date);
date.setYear(1111);
System.out.println(coach.date);

}

}

class Dater {
public Date date;

Dater(Date date) {
this.date = date;
}
}








This program will print

Mon Dec 02 16:33:48 IST 2013
Mon Dec 02 16:33:48 IST 3011


But in line date.setYear(1111); we only want to change the value of date and not coach instance But this code is changing values of date as well as coach.

So how can we avoid that :

Let's see another version of same program


import java.util.Date;

public class Refree {

public static void main(String args[]) {

Date date = new Date();
Dater coach = new Dater(date);
System.out.println(coach.date);
date.setYear(1111);
System.out.println(coach.date);

}

}

class Dater {
public Date date;

Dater(Date date) {
this.date = new Date(date.getTime());
}
}




-->

This program will print

Mon Dec 02 16:36:36 IST 2013
Mon Dec 02 16:36:36 IST 2013



So that's what we wanted..
Subscribe to: Posts (Atom)

AltStyle によって変換されたページ (->オリジナル) /