Some code to replicate the issue:
using System;
public abstract class Response { }
public abstract class Request<T> where T : Response { }
public class LoginResponse : Response { }
public class LoginRequest : Request<LoginResponse> { }
public class Program
{
static void Main(string[] args)
{
LoginRequest login = new LoginRequest();
/* Error: Cannot implicitly convert type 'LoginRequest' to 'Request' */
Request<Response> castTest = login;
/* No Error */
Request<LoginResponse> castTest2 = login;
}
}
As far as i can tell the LoginRequest class is a Request<Response> because is inherits from Request<T> and LoginResponse inherits from Response so can anybody enlighten me as to why i get the compiler error?
note: i have also tried an explicit cast
An abstract class can extend another abstract class. And any concrete subclasses must ensure that all abstract methods are implemented. Abstract classes can themselves have concrete implementations of methods. These methods are inherited just like a method in a non-abstract class.
Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods.
We can run abstract class in java like any other class if it has main() method.
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
You're getting the error because Request<Response>
and Request<LoginResponse>
are not covariant.
Just because LoginResponse
inherits from Response
doesn't mean that Request<LoginResponse>
can be treated the same as Request<Response>
. Give this article a read:
MSDN - Covariance and Contravariance in Generics
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With