java - 下面的代码违反了哪一条 SOLID 原则?

标签 java oop solid-principles

下面的代码违反了哪一条 SOLID 原则?

public class A {
  void hello(){
    //some code here
  }
}

public class B extends A {
  int i;
  void hello(){
    i++;
  }
}

我认为违反了 LSP(里氏替换原则),因为子类 B 无法替换为 A 类型的变量。我真的不确定这一点,不知何故,我认为这里没有违反任何 SOLID 原则。

我一直在考虑的另一件事是 i 是在没有任何访问修饰符的情况下声明的。这应该算违规吗?如果是,哪项违规?

最佳答案

不声明 i 私有(private)有什么问题?

摘自《Effective Java》第三版:

If a class is accessible outside its package, provide accessor methods to preserve the flexibility to change the class’s internal representation. If a public class exposes its data fields, all hope of changing its representation is lost because client code can be distributed far and wide.

However, if a class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields.

我认为何时需要公开 i 以及何时不需要公开已经非常清楚了。

另一方面,LSP 并没有被违反,因为你总是可以写

A a = new B();

通常不适合评估含义不明确的类(例如您的情况下的类 AB)违反了哪些 SOLID 原则

但是如果您知道每个类的(上下文)含义,那么我们可以做出一些评论。 (例如,Employee is-a PersonStudent is-a > Person - 所以 LSP 应该在这里工作 - 你应该能够将 Employee 对象分配给 Person 引用,类似的事情也适用于 >学生也反对)

关于java - 下面的代码违反了哪一条 SOLID 原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579148/

相关文章:

java - 无法从不同节点启动geode服务器

php - 如何检查模型是否具有特定属性?

java - Spring Security 做自动过滤注入(inject)吗?

java - 从 Java 在 MySQL 中记录 utf-8 字符串时出现问题

使用/操作 Sharepoint 2013 Rest OData XML 结果的 Java 库

php - Laravel 模型上 Trait 中的范围查询

oop - 继承和接口(interface)

java - 具有可变参数类型的接口(interface)方法

c++ - C++ 中的 "Has a"关系,拥有一个类 "implement"多个抽象基类是最佳实践吗?

c# - 按钮点击事件的编码标准