【java三大特性_面向对象】封装

本文介绍了Java中的封装概念,它是面向对象编程的三大特性之一。通过将属性设为私有并提供公共的getter和setter方法,实现了数据的隐藏和保护。举例说明了如何在Girl和Student类中应用封装,强调了在实际开发中使用getters和setters方法的重要性,并提供了快速生成这些方法的快捷键提示。

封装

概念:信息隐藏技术,通过 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值