日期:2014-05-20  浏览次数:20658 次

百分求正解!!!基础题
java的三大特性之一的封装:

什么是封装?
为什么要封装?
封装会带来哪些好处?
封装的作用是什么?
如何实现封装?

求细节,详细解答!!!说明白就有分

------解决方案--------------------
http://wq882519.blog.163.com/blog/static/981767920081015524299/
传送门
------解决方案--------------------
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
封装这种技术可以让外部通过public方法访问该类中私有的区域。如果一个区域被声明为私有,那么它将不能被外部类看到,因此被这个类所隐藏,正是出于这个原因,封装也被用来隐藏数据。
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.
封装可以被形容为一个保护屏障,它可以防止代码和数据被外部类任意的随机访问。访问数据和代码被接口严格的控制。
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
封装主要的好处是可以修改我们自己实现的代码而不必破坏其他人所写的代码。封装有可维护性,灵活性和扩展性。
以下代码就实现了一个简单的封装。
Java code
public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}

------解决方案--------------------
摘自网络,感觉这样的解释还凑合!

封装性是指的把代码封装到大括号中,只能访问自己内部的数据,外边的东西访问不了.
继承性就是一个类声明继承另一个类,那么另一个类就是它 的父类,父类里边的变量跟方法子类可以直接拿来用,除非父类的访问权限不允许.

最基础的,首先你要了解JAVA中各种修饰词:private,protected,public,friendly,它们的可视范围
一般来说,越小的可视范围带来的是节省资源,和更快的访问速度,所以如果你的类中某些成员变量或方法不需要让所有其它的类访问,最好考虑正确的使用修饰词,以屏弊它被更多的类访问到
正确的使用这些修饰词还可以避免在继承和重载重写时的方法与成员变量的重叠,既便于维护代码,也不会让人产生编码或调用时的歧义.
------解决方案--------------------
探讨

>什么是封装?
就是穿上衣服。

>为什么要封装?
有不想让人看到的地方。

>封装会带来哪些好处?
大家只会注意我长得怎么样,而不会在意我动过手术的刀疤。

>封装的作用是什么?
让大家只注意看应该看的。

>如何实现封装?
穿衣服

------解决方案--------------------
private:
自己什么都能看见。

protected:
和孩子一起洗澡。

public:
暴露狂

friendly:
sex friend
------解决方案--------------------
探讨

>什么是封装?
就是穿上衣服。

>为什么要封装?
有不想让人看到的地方。

>封装会带来哪些好处?
大家只会注意我长得怎么样,而不会在意我动过手术的刀疤。

>封装的作用是什么?
让大家只注意看应该看的。

>如何实现封装?
穿衣服

------解决方案--------------------
探讨

private:
自己什么都能看见。

protected:
和孩子一起洗澡。

public:
暴露狂

friendly:
sex friend

------解决方案--------------------
探讨

>什么是封装?
就是穿上衣服。

>为什么要封装?
有不想让人看到的地方。

>封装会带来哪些好处?
大家只会注意我长得怎么样,而不会在意我动过手术的刀疤。

>封装的作用是什么?
让大家只注意看应该看的。

>如何实现封装?
穿衣服

------解决方案--------------------
一楼给的东西很有用,楼主看看呢。