2020.8.17
阿新 • • 發佈:2020-12-17
學習內容
1.多邊形繼承
1 //父類: 2 public class CPolygon { 3 protected int width,height; 4 public void setValues(int a,int b) 5 { 6 width=a; 7 height=b; 8 } 9 } 10 //子類1:長方形 11 public class CRectangle extends CPolygon { 12 public int area() { 13 return width*height; 14 } 15 } 16 //子類2:三角形 17 public class CTriangle extends CPolygon { 18 public int area() { 19 return (width*height)/2; 20 } 21 } 22 //實現類: 23 public class main1 { 24 public static void main(String[] args) { 25 CRectangle rect=new CRectangle(); 26 CTriangle trgl=new CTriangle(); 27 rect.setValues(4, 5); 28 trgl.setValues(4, 5); 29 System.out.println("長方形面積:"+rect.area()); 30 System.out.println("三角形面積:"+trgl.area()); 31 } 32 }
2.日期時間類
1 //介面1:日期 2 public interface Date { 3 public void setDate(int y,int mo,int d); 4 public void displayDate(); 5 } 6 //介面2:時間 7 public interface Time { 8 public void setTime(int h,int mi,int s); 9 public void displayTime(); 10 } 11 //實現類: 12 public class Datetime implements Date,Time { 13 protected int year,month,day,hour,minute,second; 14 public void setDate(int y,int mo,int d) { 15 year=y; 16 month=mo; 17 day=d; 18 } 19 public void displayDate() { 20 System.out.println(year+"-"+month+"-"+day); 21 } 22 public void setTime(int h,int mi,int s) { 23 hour=h; 24 minute=mi; 25 second=s; 26 } 27 public void displayTime() { 28 System.out.println(hour+":"+minute+":"+second); 29 } 30 public static void main(String[] args) { 31 Datetime dt=new Datetime(); 32 dt.setDate(2020, 5, 20); 33 dt.setTime(20, 13,14); 34 dt.displayDate(); 35 dt.displayTime(); 36 } 37 }