以下代码违反了哪项 SOLID 原则?

Which SOLID principle is violated in the following code?

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

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

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

我认为违反了LSP(Liskov Substitution Principle),因为子类B不能代入A类型的变量。我真的不确定这一点,不知何故我认为这里违反了 SOLID 原则的 none。

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

不声明 i 私有有什么问题?

来自有效 Java 第 3 版:

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();

用class含义不明确的词(如class中的AB来评价违反了哪些SOLID原则一般是不合适的你的情况)

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