From 24a3a24382a781ddb2e2b4cf33266634a72dc89a Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Mon, 21 Sep 2026 10:44:04 +0800 Subject: [PATCH] =?UTF-8?q?day06--=E9=9D=A2=E5=90=91=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=E4=B9=8B=E5=B0=81=E8=A3=85=5F=E6=A6=82=E8=BF=B0=E5=92=8C?= =?UTF-8?q?=E6=AD=A5=E9=AA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day06/src/com/inmind/private02/Demo03.java | 21 ++++++++++++ day06/src/com/inmind/private02/Student.java | 37 +++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 day06/src/com/inmind/private02/Demo03.java create mode 100644 day06/src/com/inmind/private02/Student.java diff --git a/day06/src/com/inmind/private02/Demo03.java b/day06/src/com/inmind/private02/Demo03.java new file mode 100644 index 0000000..31f81fd --- /dev/null +++ b/day06/src/com/inmind/private02/Demo03.java @@ -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()); + } +} diff --git a/day06/src/com/inmind/private02/Student.java b/day06/src/com/inmind/private02/Student.java new file mode 100644 index 0000000..e71448e --- /dev/null +++ b/day06/src/com/inmind/private02/Student.java @@ -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; + } + +}