Java基础学习:面向对象之封装

后端学习评论5.1K字数 802阅读2分40秒阅读模式
Java基础学习:面向对象之封装

来源:慕课

 

 文章源自亦枫博客-https://yflad.cn/2010.html

1、定义

  • 将类的某些信息隐藏在类内部,不允许外部程序直接访问
  • 通过该类提供的方法来实现对隐藏信息的操作和访问
  • 隐藏对象的信息
  • 留出访问的接口

 文章源自亦枫博客-https://yflad.cn/2010.html

2、封装的特点:

1)只能通过规定的方法访问数据文章源自亦枫博客-https://yflad.cn/2010.html

2)隐藏类的实例细节,方便修改和实现文章源自亦枫博客-https://yflad.cn/2010.html

 文章源自亦枫博客-https://yflad.cn/2010.html

3、封装的好处:

  1. 将变化隔离
  2. 方便使用
  3. 提高复用性
  4. 提高安全性

 文章源自亦枫博客-https://yflad.cn/2010.html

4、封装的实现:

对外提供 pulbic 修饰的 getXX() 和 setXX()文章源自亦枫博客-https://yflad.cn/2010.html

1)封装首先会通过[code]private[/code]私有化变量,限制对类属性的访问文章源自亦枫博客-https://yflad.cn/2010.html

2)对每个值属性提供对外的公共方法访问,也就是创建一对赋取值方法,用于对私有属性的访问文章源自亦枫博客-https://yflad.cn/2010.html

package com.yflad.oop;
/**
 * java中的封装思想
 */
public class Person {
   //私有的成员变量
	private String name;
	private int age=16;
	//其它类要想访问本类的属性,需要对外提供一个公共的方法
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

 文章源自亦枫博客-https://yflad.cn/2010.html

3)调用文章源自亦枫博客-https://yflad.cn/2010.html

package com.auto.privatedemo;

public class TestPerson {
  public static void main(String[] args) {
	Person p=new Person();
	p.setName("李四");
	String name=p.getName();   //通过get方法获取属性
	System.out.println(name);
 }
}

 文章源自亦枫博客-https://yflad.cn/2010.html 文章源自亦枫博客-https://yflad.cn/2010.html

继续阅读
扫扫关注公众号
weinxin
我的微信
扫扫体验小程序
weinxin
我的公众号
亦枫
  • 本文由 发表于 2018年12月5日 17:46:29
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定