JAVA——封装

一、封装的作用

1.外界不希望能够直接访问我的数据。

 2.希望外界传递给类的内部的数据能够得到数据校验,不得任其随意修改。


 二、封装的概念

 对数据进行访问权限控制,主要依赖的就是访问权限修饰符。

访问权限修饰符: public protected [default] private


三、 如何来对数据进行封装?

 1.  对需要封装的数据成员使用访问权限修饰符(private)加以修饰。

 2.  在类的内部提供对外访问渠道 (set get方法)。

 3.  使用代码对数据做数据校验 (一般省略不写,看需求实现)。

四、封装代码演示

下面用代码演示封装一个苹果手机类:

package com.sxt.privatedemo;

public class PrivateDemo02 {

public static void main(String[] args) {

mobile.setBrand("hello");

mobile.show();

AppleMobile mobile2 = new AppleMobile();

mobile2.setBrand("world");

mobile2.show();

}

}

class AppleMobile {

private String brand;

private String color;

private double price;

public void call() {

System.out.println("AppleMobile.call()");

}

public String getBrand() {

return this.brand;

}

public void setBrand(String brand) {

this.brand = brand;

}

public String getColor() {

getPrice();

return color;

}

public void setColor(String color) {

this.color = color;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public void test(AppleMobile mobile) {

System.out.println(mobile.brand);

}

public void show() {

this.test(this);

}

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 原文链接 http://www.runoob.com/java/java-encapsulation.html...
    zealotabc阅读 157评论 0 0
  • 在面向对象程式设计方法中,封装(Encapsulation)是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的...
    海人为记阅读 321评论 0 0
  • 一、实现Java封装的步骤 修改属性的可见性来限制对属性的访问(一般限制为private),例如: public ...
    眼前人心上人_9a6a阅读 872评论 0 0
  • 一.成员变量与局部变量的区别 成员变量:在类中定义,用来描述对象将要有什么(属性)。可被本类方法和其他跟当前类有关...
    jeffierw阅读 631评论 0 0
  • 每天晚上,我都要早早洗漱,等一个重要时刻,眼睛盯着手机屏幕一动不动,我很想主动联系他,可我又不敢,我不想那么主动,...
    追梦的ai人阅读 273评论 0 0

友情链接更多精彩内容