英文:
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<String> exampleList = new ArrayList<>();
and the other one
List<String> exampleList = new LinkedList<>();
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论