英文:
Are instance and object different?
问题
以下哪些是正确的?
- b 不是 A 的实例
- b 不是 C 的实例
英文:
Which of the following is(are) true?
- b is not an instance of A
- b is not an instance of C
class A{}
class B extends A{}
class C extends B{}
B b=new B();
答案1
得分: 1
为了帮助您理解这个概念,您可以将抽象名称A、B、C
替换为常见的示例,比如Animal(动物)、Feline(猫科动物)、Cat(猫)
比如:
class Animal {}
class Feline extends Animal {}
class Cat extends Feline {}
这样您的问题就变成了:
1. 一个 Feline 可能不是 Animal
2. 一个 Feline 可能不是 Cat
- 错误,每个 Feline 实例都是一个 Animal。Feline 继承自 Animal
- 正确,不是每个 Feline 都是 Cat。Feline 并未继承 Cat
正如 @AndyTurner 提到的,您可以使用 instanceOf
来进行检查。
英文:
To help you understand this concept you might replace abstract name A, B, C
with common example such as Animal, Feline, Cat
Like
class Animal {}
class Feline extends Animal {}
class Cat extends Feline {}
And your question becomes :
1. One feline might not be an Animal
2. One feline might not be a Cat
- False every Feline instance is an Animal. Feline extends Animal
- True not every feline are Cat. Feline does not extend Cat
As mentionned by @AndyTurner you might use instanceOf
to check it out
答案2
得分: 0
在Google上搜索Liskov替换原则。它规定:
> 在计算机程序中,如果S是T的子类型,那么类型T的对象可以被类型S的对象替代 - 维基百科
> "b不是A的实例"是错误的。
局部变量"b"是类"B"的一个实例。类"B"是类"A"的一个实例,因为它扩展了"A",因此类"B"拥有的一切,"A"也拥有。
> "b不是C的实例"是正确的。
局部变量"b"是类"B"的一个实例。类"B"不是类"C"的一个实例,因为类"B"包含了类"B"以及类"A"的所有内容,它对类"C"一无所知。
英文:
Search for the Liskov substitution principle on Google. It states that:
> In a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S - Wikipedia
> "b is not an instance of A" is false.
The local variable "b" is an instance of class "B". Class "B" is an instance of class "A" because it extends "A" and therefore everything that class "B" is, "A" is too.
> "b is not an instance of C" is true.
The local variable "b" is an instance of class "B". Class "B" is not an instance of C" because class "B" is everything that class "B" is and class "A", it knows nothing about class "C"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论