У нас вы можете посмотреть бесплатно Understanding Java Generics: Why Returning a Generic Type Parameter Can Fail или скачать в максимальном доступном качестве, видео которое было загружено на ютуб. Для загрузки выберите вариант из формы ниже:
Если кнопки скачивания не
загрузились
НАЖМИТЕ ЗДЕСЬ или обновите страницу
Если возникают проблемы со скачиванием видео, пожалуйста напишите в поддержку по адресу внизу
страницы.
Спасибо за использование сервиса ClipSaver.ru
Explore why Java generic methods with bounded type parameters can't safely return an instance of a specific implementing class, and how unchecked casts fit into this scenario. --- This video is based on the question https://stackoverflow.com/q/79438418/ asked by the user 'davidalayachew' ( https://stackoverflow.com/u/10118965/ ) and on the answer https://stackoverflow.com/a/79438437/ provided by the user 'Slaw' ( https://stackoverflow.com/u/6395627/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions. Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Having trouble with generics Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l... The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license. If anything seems off to you, please feel free to drop me a comment under this video. --- Introduction When working with Java generics, you might hit a confusing compiler error when trying to return an instance of a class implementing multiple generic interfaces from a method whose return type is a generic type parameter bounded by those interfaces. This article explains why the compiler complains in this scenario and how it relates to Java's type safety. The Core Problem Suppose you have two generic interfaces: [[See Video to Reveal this Text or Code Snippet]] And a record that implements both: [[See Video to Reveal this Text or Code Snippet]] Now, imagine a generic method with a type parameter D that extends both M<D1, D2> and F<D1, D2>: [[See Video to Reveal this Text or Code Snippet]] You might expect this to compile since A<A1, A2> implements both interfaces with matching type parameters. However, the compiler complains about incompatible types. Why the Compiler Rejects This Key point: The type parameter D is determined by the caller of the method, not by the method implementation. This means D can be any type meeting the bounds: Implements M<D1, D2> Implements F<D1, D2> For example, the caller could expect an instance of a different class Other that also implements these interfaces. So, if the method always returns an instance of A, it may violate the caller's expectations if D is not A. This potential mismatch causes the compiler to reject returning new A<>(d1, d2) as D. Illustrative Example [[See Video to Reveal this Text or Code Snippet]] Here, the caller expects OtherFooBar, but the method returns FooBar. Because they are distinct types that implement the same interfaces, assigning FooBar to R (which could be anything compatible) is unsafe. What About Casting? You might try to force it with an unchecked cast: [[See Video to Reveal this Text or Code Snippet]] This compiles but shifts the problem to runtime, where misuse can cause ClassCastException. Use unchecked casts only when you are certain the cast is safe in all contexts. Summary The method's generic return type D is defined by the caller's expectations and can be any compatible subtype. Returning a specific implementation like A doesn't guarantee compatibility with all possible D types. Java's compiler enforces this to maintain type safety. Unchecked casts can bypass the restriction but at the cost of safety. Understanding that generic type parameters in method signatures are placeholders constrained only by bounds—and are not fixed to a specific class—helps clarify this common confusion. Further Reading Java Generics and Type Safety [Effective Java, 3rd Edition by Joshua Bloch - Item 27: Eliminate unchecked warnings]