java - 抽象和封装有什么区别?

标签 java oop

<分区>

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。列表、数组、字典和任何其他类型的集合类都实现了 IEnumerableforeach 循环结构和整个 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);

您可以同时使用两者,就像我对 IAnimalIsHealthy 所做的那样。 IAnimal 是一个抽象,只有一个get 访问器,IsHealthy 上没有set 访问器是封装。

关于java - 抽象和封装有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966710/

相关文章:

java - 在带有finally block 的方法中放置return 语句

java - 使用 Java 动态创建 MySQL 表列

java - 为什么Java允许使用对象实例访问静态成员

python - 使用属性装饰器的Python类中的属性行为

java - ApplicationEventPublisher NullPointerException

java - 从java类中的spring文件访问属性

Java、PostgreSQL 和 Hibernate : Select statement with nested strings

java - 读取器/写入器/流何时被标识为开放?

c++ - 将类实例移至类成员后无法初始化类实例?

php - fatal error : Function name must be a string in.。 PHP错误