Java - 定义 - “替换原则”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6317121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:20:53  来源:igfitidea点击:

Java - definition - "principle of substitution"

java

提问by Tom

I read a summary which always use the definition "principle of substitution" when it talk about inheritance. But It doesn't explain the meaning of this principle.

我读了一篇关于继承的摘要,它总是使用“替换原则”的定义。但它并没有解释这个原理的含义。

What is this principle?

这是什么原理?

Thank you.

谢谢你。

采纳答案by Scott C Wilson

You probably know it, just not by this name.

你可能知道,只是不知道这个名字。

http://en.wikipedia.org/wiki/Liskov_substitution_principle

http://en.wikipedia.org/wiki/Liskov_substitution_principle

It just says "If S is a T, then references to T can be changed to references to S."

它只是说“如果 S 是 T,则对 T 的引用可以更改为对 S 的引用。”

回答by irreputable

It means plainly: a subclass must honor the contract set by the super class.

意思很明确:子类必须遵守超类设定的契约。

If you extend a super class, you should read its document and implement as it dictates. That's all.

如果你扩展一个超类,你应该阅读它的文档并按照它的指示实现。就这样。

If I hear one more time "Liskov substitution" I'm going to kill a kitten.

如果我再听到一次“Liskov 替换”,我会杀死一只小猫。

回答by Agustin Cautin

Basically says that a class that implements a determined interface can be replaced by any other implementing the same inteface. You can found more information about this in Liskov's Substitution Principlequoting the definition:

基本上是说一个实现确定接口的类可以被任何其他实现相同接口的类替换。您可以在引用定义的Liskov 替换原则中找到有关此内容的更多信息:

"If a program module is using the reference of a Base class, then it should be able to replace the Base class with a Derived class without affecting the functioning of the program module. "

“如果程序模块使用基类的引用,那么它应该能够用派生类替换基类,而不会影响程序模块的功能。”

回答by Stas Jaro

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it

使用指向基类的指针或引用的函数必须能够在不知情的情况下使用派生类的对象

it is also known as the liskov substitution

它也被称为 liskov 替换

回答by Woot4Moo

The principle of substitution or Liskov Substitution Principle (LSP) basically states that an object should only be in a hierarchy if in every scenario that object can be used as its parent. For a concrete example:

替换原则或 Liskov 替换原则 (LSP) 基本上指出,如果在每种情况下该对象都可以用作其父对象,则该对象仅应位于层次结构中。举个具体的例子:

public class Rectangle    {  
   //Stuff about rectangles    }  

public class Square extends Rectangle    {  
   //VIOLATES LSP!!  
} 

explanation here

解释在这里

public abstract class Shape  
{  
   //stuff about shapes  
}  

public class Square extends Shape  
{  
   //Square  
}  

public class Rectangle extends Shape  
{  
    //Rectangle  
}