JAVA——封装

时间:2019-04-19
本文章向大家介绍JAVA——封装,主要包括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);

}

}