首先,了解封装的定义:封装(英语:Encapsulation)是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法。提高代码的复用性和安全性
然后了解了四种访问权限修饰符知道他们的权限范围由大到小是:
public(公共的)可以被所有其他类所访问。
default(默认的)只能被自己访问和修改。
protected(受保护的)自身,子类及同一个包中类可以访问。
private(私有的)同一包中的类可以访问。
在没有具体些某一类修饰符时,默认修饰符为default。
下面写一个简单的封装具体例子。
要求:定义一个Person类,里面有三个私有属性:名字,身高,体重和一个名为showInf()的方法。
类部分: static class Person { private int high; private String name; private int weight; /*属性为私有,访问要通过成对出现的public类。创建一对赋值取值的方法来提供外部程序对类中的私有属性进行访问。有三个私有属性所以需要六个public才能完成。*/ public int getHigh(){ return high; } public void setHigh(int high){ //this是一个关键字,翻译为:这个。this指向当前正在执行这个动作的对象 this.high = high; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getWeight(){ return weight; } public void setWeight(int weight){ this.weight = weight; } void showInf() { System.out.println(name+"身高"+high+"体重"+weight); }
主方法部分:
package edu.test; //调用get就是取属性值,调用set就是给属性赋值。 public class Test5 { public static void main(String[] args) { Person person = new Person();//定义一个对象用来调用类方法。 person.getName(); person.setName("张三"); person.getHigh(); person.setHigh(170); person.getWeight(); person.setWeight(130); person.showInf();//最后调用方法打印。 }package edu.test; public class Test5 { public static void main(String[] args) { Person person = new Person(); person.getName(); person.setName("张三"); person.getHigh(); person.setHigh(170); person.getWeight(); person.setWeight(130); person.showInf(); } static class Person { private int high; private String name; private int weight; public int getHigh() { return high; } public void setHigh(int high) { this.high = high; } public void setName(String name) { this.name = name; } public void setWeight(int weight) { this.weight = weight; } public String getName() { return name; } public int getWeight() { return weight; } void showInf() { System.out.println(name+"身高:"+high+"体重:"+weight); } } }
结果如下:
本文含有隐藏内容,请 开通VIP 后查看