对封装类的使用
申明类,执行构造方法
Student stu=new Student();
添加成员变量的参数
stu.setName("钱*");
stu.setAge(18);
stu.setMale(true);
显示结果
System.out.println("学生姓名是:"+stu.getName()+",年龄为:"+stu.getAge()+",是男性吗?"+stu.isMale());
调用对象的方法并显示
stu.sayHello("汤**");
System.out.println(stu);//stu就是this
注意事项
既然对象类里面构造方法带有参数
为什么还要setter和getter方法:
为了更好的设置成员变量的值(成员变量的属性值并不是一成不变的,如下:
Student stu2=new Student("宋**",12,true);
System.out.println("学生姓名是:"+stu2.getName()+",年龄为:"+stu2.getAge()+",是男性吗?"+stu2.isMale());
stu2.setAge(16);
System.out.println("学生姓名是:"+stu2.getName()+",年龄为:"+stu2.getAge()+",是男性吗?"+stu2.isMale());
显示结果
注:两串为地址值(this与创建对象的地址值比较,见上篇伏笔)