Demo entry 3548715

tran

   

Submitted by anonymous on Jan 18, 2016 at 02:34
Language: Java. Code size: 2.4 kB.

public class ShallowCopy {
   public static void main(String []args) throws CloneNotSupportedException {
      SinhVien sv1 = new SinhVien("111", "NVA", new Date(1, 1, 2001), 7.0);
      SinhVien sv3 = new SinhVien("333", "NVB", new Date(2, 2, 2002), 9.0);
      
      System.out.print("SV1: ");
      sv1.hienthi();
      System.out.print("SV3: ");
      sv3.hienthi();
      System.out.println("-----------------");

      SinhVien sv2 = sv1;     //sao chép tham chiếu
      sv2.ganDiemTB(8.0);     //sv1 sẽ thay đổi theo
      sv2.layNgaysinh().set(2, 2, 2002);

         
      SinhVien sv4 = (SinhVien)sv3.clone();     //sao chép cạn
      sv4.ganDiemTB(9.5);                       //sv3 không thay đổi diemTB
      sv4.layNgaysinh().set(3, 3, 2003);        //sv3 bị thay đổi ngaysinh

      System.out.println("Gan tham chieu:");
      System.out.print("SV1:");
      sv1.hienthi();
      System.out.print("SV2:");
      sv2.hienthi();

      System.out.println("\nSao chep can:");
      System.out.print("SV3:");
      sv3.hienthi();
      System.out.print("SV4:");
      sv4.hienthi();

   }   

}

class Date {
   private int ngay, thang, nam;

   public Date(int ngay, int thang, int nam) {
      this.ngay = ngay;
      this.thang = thang;
      this.nam = nam;
   }

   public void set(int ngay, int thang, int nam) {
      this.ngay = ngay;
      this.thang = thang;
      this.nam = nam;
   }

   public void hienthi() {
      System.out.print(ngay + "/" + thang + "/" + nam);
   }

}

class SinhVien implements Cloneable {
   private String mssv, hoten;
   private Date ngaysinh;
   private double diemTB;

   public SinhVien(String mssv, String hoten, Date ngaysinh, double diemTB) {
      this.mssv = mssv;
      this.hoten = hoten;
      this.ngaysinh = ngaysinh;
      this.diemTB = diemTB;
   }

   public void hienthi() {
      System.out.print("{" + mssv + "; " + hoten + "; ");
      ngaysinh.hienthi();
      System.out.println("; " + diemTB + "}");
   }

   public void ganDiemTB(double diemTB) {
      this.diemTB = diemTB;
   }

   public Date layNgaysinh() {
      return ngaysinh;
   }

   public void ganHoten(String hoten) {
      this.hoten = hoten;
   }

   public Object clone() throws CloneNotSupportedException {
      return super.clone();
   }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).