你的位置:首页 > Java教程

[Java教程]包和访问权限2


在包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 }

结果: