封装
概念:信息隐藏技术,通过 private protected public实现封装,定义如何引用对象的数据。
封装属性
将属性私有化,可以加权限修饰符,private修饰
提供public修饰方法来访问
外界通过方法访问属性
//例子01
public class Encapsulation01 {
public static void main(String[] args) {
Girl g = new Girl();
/* g.age = 31;
System.out.println(g.age);*/
g.setAge(50);
System.out.println(g.getAge());
}
}
public class Girl {
//属性
private int age;
public void setAge(int age){
if(age > 30){
this.age = 18;
}else{
this.age = age;
}
}
public int getAge(){
return age;
}
}
//例子02
public class Encapsultion {
public static void main(String[] args){
Student s1 = new Student();
s1.setAge(18);
s1.setName("平安");
s1.setSex("男");
System.out.println("姓名:"+ s1.getName() + " 性别:" +s1.getSex() + " 年龄:" + s1.getAge());//姓名:平安 性别:男 年龄:18
Student s2 = new Student(19,"闪闪" ,"xnsuicai");
System.out.println("姓名:"+ s2.getName() + " 性别:" +s2.getSex() + " 年龄:" + s2.getAge());//姓名:闪闪 性别:输入有误 年龄:19
}
}
public class Student {
int age;
String name ;
String sex;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
if(sex.equals("男") || sex.equals("男")){
this.sex = sex;
}else{
this.sex = "输入有误";
}
}
public Student(){
}
public Student(int age ,String name , String sex){
this.age = age;
this.name = name ;
setSex(sex);
}
}
封装使用
实际开发中会使用get set 方法
使用快捷键:alt + insert
本文介绍了Java中的封装概念,它是面向对象编程的三大特性之一。通过将属性设为私有并提供公共的getter和setter方法,实现了数据的隐藏和保护。举例说明了如何在Girl和Student类中应用封装,强调了在实际开发中使用getters和setters方法的重要性,并提供了快速生成这些方法的快捷键提示。
211

被折叠的 条评论
为什么被折叠?



