在包a中編寫一個類Father,具有屬性:年齡(私有)、姓名(公有);
具有功能:工作(公有)、開車(公有)。
在包a中編寫一個子類Son,具有屬性:年齡(受保護的)、姓名;
具有功能:玩(私有)、學習(公有)。
最後在包b中編寫主類Test,在主類的main方法中測試類Father與類Son。
Father:
1 package pack1; 2 3 public class Father { 4 private int age; 5 6 public int getAge() { 7 return age; 8 } 9 10 public void setAge(int age) { 11 this.age = age; 12 } 13 14 public String name; 15 16 public void work() { 17 System.out.println(name + ": I have a job."); 18 } 19 20 public void drive() { 21 System.out.println(name + ": I have a car, I'm driving."); 22 } 23 }
Son:
1 package pack1; 2 3 public class Son { 4 5 protected int age; 6 7 public void setAge(int age) { 8 this.age = age; 9 } 10 11 public int getAge() { 12 return age; 13 } 14 15 private String name; 16 17 public void setName(String name) { 18 this.name = name; 19 } 20 21 public String getName() { 22 return name; 23 } 24 25 private int play() { 26 System.out.println(name + ": I like to play !"); 27 return age; 28 } 29 public int getPlay(){ 30 return age; 31 } 32 33 public void study() { 34 System.out.println(name + ": I like to study !"); 35 } 36 }
Text:
1 package pack2; 2 3 import pack1.Father; 4 import pack1.Son; 5 6 public class Text_F { 7 8 public static void main(String[] args) { 9 Father f1 = new Father(); 10 f1.setAge(55); 11 f1.name = "張三"; 12 13 f1.drive(); 14 f1.work(); 15 int a = f1.getAge(); 16 System.out.println(f1.name + "的年齡:" + a + "歲。"); 17 18 Son s1 = new Son(); 19 s1.setAge(17); 20 s1.setName("張三三"); 21 s1.study(); 22 int b = s1.getAge(); 23 System.out.println(s1.getName() + "的年齡:" + b + "歲。"); 24 25 } 26 27 }
結果: