Java 33. Hiểu rõ phương thức toString trong lập trình Java



    Bản quyền thuộc về TITV.vn, 
    vui lòng không đăng tải lại nội dung từ trang này.

    Video giải thích chi tiết


     Chương trình 

    
    
    public class MyDate {
    	private int day;
    	private int month;
    	private int year;
    	
    	public MyDate(int day, int month, int year) {
    		if (day >= 1 && day <= 31) {
    			this.day = day;
    		} else {
    			this.day = 1;
    		}
    		if (month >= 1 && month <= 12) {
    			this.month = month;
    		} else {
    			this.month = 1;
    		}
    		if (year >= 1) {
    			this.year = year;
    		}else {
    			this.year = 1;
    		}
    	}
    
    	public int getDay() {
    		return day;
    	}
    
    	public void setDay(int day) {
    		if (day >= 1 && day <= 31) {
    			this.day = day;
    		} 
    	}
    
    	public int getMonth() {
    		return month;
    	}
    
    	public void setMonth(int month) {
    		if (month >= 1 && month <= 12) {
    			this.month = month;
    		}
    	}
    
    	public int getYear() {
    		return year;
    	}
    
    	public void setYear(int year) {
    		if (year >= 1) {
    			this.year = year;
    		}
    	}
    
    	@Override
    	public String toString() {
    		return "MyDate [day=" + day + ", month=" + month + ", year=" + year + "]";
    	}
    
    //	@Override
    //	public String toString() {
    //		return this.day + "/" + this.month + "/"+this.year;
    //	}
    	
    	
    }
    
    
         
    
           
    public class Test {
    	public static void main(String[] args) {
    		MyDate md1 = new MyDate(15, 5, 2025);
    		MyDate md2 = new MyDate(11, 1, 2021);
    		MyDate md3 = new MyDate(30, 3, 2030);
    		
    		System.out.println(md1); // 15/5/2021
    		System.out.println(md2);
    		System.out.println(md3);
    	}
    }
    
    
      

    Bạn có thể thích những bài đăng này:

    Không có nhận xét nào:

    Đăng nhận xét