<分区>
Java 中的封装和抽象到底有什么区别?任何简短的例子也将不胜感激。
<分区>
Java 中的封装和抽象到底有什么区别?任何简短的例子也将不胜感激。
最佳答案
抽象和封装是两种味道很好的组合。
封装 正在最小化您向代码用户公开的内容。该“用户”可能是您的其余代码,或者是使用您发布的代码的任何人。
封装有一些明确的好处:
我不懂Java,但这里有一个用C#封装的小例子:
public class Giraffe
{
public Giraffe(int heightInFeet)
{
this.heightInFeet = heightInFeet;
this.numberOfSpots = heightInFeet * 72;
}
public override string ToString()
{
return "Height: " + heightInFeet + " feet"
+ " Number of Spots: " + numberOfSpots;
}
private int heightInFeet;
private int numberOfSpots;
}
它没有公开numberOfSpots
,而是封装在类中,并通过ToString
方法公开。
Abstraction 使用扩展点将选择推迟到运行确切代码的不同部分。该选择可以在您的程序的其他地方、另一个程序中或在运行时动态地进行。
抽象也有很大的好处:
C# 中一个高度使用的抽象是 IEnumerable
。列表、数组、字典和任何其他类型的集合类都实现了 IEnumerable
。 foreach
循环结构和整个 LINQ 库都基于该抽象:
public IEnumerable<int> GetSomeCollection()
{
// This could return any type of int collection. Here it returns an array
return new int[] { 5, 12, 7, 14, 2, 3, 7, 99 };
}
IEnumerable<int> someCollectionOfInts = GetSomeCollection();
IEnumerable<string> itemsLessThanFive = from i in someCollectionOfInts
where i < 5
select i.ToString();
foreach(string item in itemsLessThanFive)
{
Console.WriteLine(item);
}
您也可以轻松编写自己的抽象:
public interface IAnimal
{
bool IsHealthy { get; }
void Eat(IAnimal otherAnimal);
}
public class Lion : IAnimal
{
public Lion()
{
this.isHealthy = true;
}
public bool IsHealthy
{
get { return isHealthy; }
}
void Eat(IAnimal otherAnimal)
{
if(otherAnimal.IsHealthy && !(otherAnimal is SlimeMold))
{
isHealthy = true;
}
else
{
isHealthy = false;
}
}
private bool isHealthy;
}
IAnimal someAnimal = PullAnAnimalOutOfAWoodenCrate();
Console.WriteLine("The animal is healthy?: " + someAnimal.IsHealthy);
您可以同时使用两者,就像我对 IAnimal
和 IsHealthy
所做的那样。 IAnimal
是一个抽象,只有一个get
访问器,IsHealthy
上没有set
访问器是封装。
关于java - 抽象和封装有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966710/