day06--面向对象之封装_概述和步骤
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package com.inmind.private02;
|
||||
|
||||
public class Demo03 {
|
||||
public static void main(String[] args) {
|
||||
//创建一个学生对象
|
||||
Student s = new Student();
|
||||
//其他类无法对private私有化属性进行随意的访问了!!!
|
||||
/*s.name = "张三";
|
||||
s.age = 120;*/
|
||||
s.setName("张三");
|
||||
s.setAge(21);
|
||||
showStudent(s);
|
||||
}
|
||||
|
||||
public static void showStudent(Student s){
|
||||
/*System.out.println(s.name);
|
||||
System.out.println(s.age);*/
|
||||
System.out.println(s.getName());
|
||||
System.out.println(s.getAge());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.inmind.private02;
|
||||
|
||||
/*
|
||||
面向对象之封装的作用:代码的安全性
|
||||
如何封装???
|
||||
封装的步骤
|
||||
1. 使用 private 关键字来修饰成员变量。
|
||||
2. 对需要访问的成员变量,提供对应的一对 getXxx 方法 、setXxx 方法。
|
||||
*/
|
||||
public class Student {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
//定义一对get/set方法对私有的,允许访问的 属性进行操作
|
||||
public String getName(){
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String n){
|
||||
name = n;
|
||||
}
|
||||
|
||||
|
||||
public int getAge(){
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int a){
|
||||
if (a > 100 || a < 0) {
|
||||
System.out.println("您输入的年龄有误,只能是0~100");
|
||||
//此处直接将方法结束即可
|
||||
return;
|
||||
}
|
||||
age = a;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user