下面的代码违反了哪一条 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();
通常不适合评估含义不明确的类(例如您的情况下的类 A
和 B
)违反了哪些 SOLID 原则
但是如果您知道每个类的(上下文)含义,那么我们可以做出一些评论。 (例如,Employee
is-a
Person
和 Student
is-a
> Person
- 所以 LSP 应该在这里工作 - 你应该能够将 Employee
对象分配给 Person
引用,类似的事情也适用于 >学生
也反对)
关于java - 下面的代码违反了哪一条 SOLID 原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579148/