首先定义一个名为 Student 的类,代码如下:
1 public class Student { 2 // 学生类 3 }
1 public class Student { 2 public String Name; // 学生姓名 3 public int Age; // 学生年龄 4 private boolean Sex; // 学生性别 5 }
1 public boolean isSex() { 2 return Sex; 3 } 4 public void setSex(boolean sex) { 5 this.Sex = sex; 6 }
1 public static void main(String[] args) { 2 Student zhang = new Student(); // 创建第一个实例 3 zhang.Name = "张子同"; 4 String isMan = zhang.isSex() ? "女" : "男"; 5 System.out.println("姓名:" + zhang.Name + "性别:" + isMan + "年龄:" + zhang.Age); 6 Student li = new Student(); // 创建第二个实例 7 li.Name = "李子文"; 8 li.Sex = true; 9 li.Age = 15; 10 String isWoman = li.isSex() ? "女" : "男"; 11 System.out.println("姓名:" + li.Name + "性别:" + isWoman + "年龄:" + li.Age); 12 }
姓名:张子同性别:男年龄:0
姓名:李子文性别:女年龄:15
由输出结果可以看到,在第一个实例 zhang 中由于仅设置了 Name 属性的值,所以 boolean 类型的 Sex 默认使用值 false,int 类型的 Age 默认使用值 0。第二个实例 li 同时设置了这三个属性的值。