为什么在Java中将不同于对象引用类型的类型分配给对象?

huangapple go评论57阅读模式
英文:

Why do we assign types to objects that are different to an object's reference type in Java?

问题

Programmers sometimes use this approach because they want to take advantage of polymorphism or assign a subclass instance to a superclass reference variable. This allows for flexibility and can be useful in certain situations.

英文:

Java Newbie here

New instances are stored in variables. However, I see sometimes, that the type of the variable is different from the reference type of the object.

Y y = new x

Why do programmers do this?

答案1

得分: 0

因为有时您对不同的实现使用通用接口。例如

List<String> exampleList = new ArrayList<>();

和另一个

List<String> exampleList = new LinkedList<>();

接口 List 为我们提供了这两种实现的相同方法,但这些方法的工作方式取决于实现方式。欢迎。

英文:

Because sometimes you have common interface for different implementations. For example

List&lt;String&gt; exampleList = new ArrayList&lt;&gt;(); 

and the other one

List&lt;String&gt; exampleList = new LinkedList&lt;&gt;();

Interface List provide for us the same methods for this two implementations, but how this methods works depends on implementation. Welcome

答案2

得分: 0

大多数情况下,你的示例中的Y是一个接口,因此你可以在不改变应用程序的其余部分的情况下稍后更改实现。

英文:

Most time Y in your example is an interface so you can change later the Implementation without to change the rest of your application

huangapple
  • 本文由 发表于 2020年8月6日 02:56:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63271820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定