Anjana Ethilkandy
Anjana Ethilkandy

Reputation: 21

How can i call the child method after downcasting parent object to child object?

I have Request class which is a parent class and AddressRequest class which extends Request.

public AddressRequest extends Request
{

    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

}

I have the input data in the Request object. how can I set the userId to the same object by calling the setter method in the child class.

I downcasted the Request object to AddressRequest object and tried calling the setter method which is throwing CTE.

Request request= new AddressRequest ();
request=(AddressRequest )inputRequest;
request.setUserId("11");

How can i call the child method after downcasting object?

Upvotes: 1

Views: 2034

Answers (2)

avr
avr

Reputation: 4883

You cannot downcast superclass reference type which is an instance of superclass.

You can downcast superclass reference type which is an instance of subclass.

You are stuck with case #1 where your inputRequest is of type Request and an instance of Request i.e

Request inputRequest = new Request();

You can't cast this to AddressRequest, if you try to do so you will get ClassCastException as object of Request is neither subclass of AddressRequest nor compatible with it.

But if your inputRequest is of type Request and an instance of AddressRequest then you would have succeeded. i.e

Request inputRequest = new AddressRequest();

You can fairly cast this to your subclass(AddressRequest) and apply it's methods.

Summary:

Request req1 = new Request();
Request req2 = new AddressRequest();
Request req3 = new SubClassOfAddressRequest();

You can't cast req1 to AddressRequest : req1 is object of Request and it is not compatible with AddressRequest.

You can cast req2 to AddressRequest : req2 is object of AddressRequest and is compatible with AddressRequest.

You can still cast req3 to AddressRequest : req3 is an object of AddressRequest's SubClass(this is kind of upcasting).

Hope this helps!

Upvotes: 1

Ishnark
Ishnark

Reputation: 681

So, essentially what you're doing here is dynamic dispatch. by specifying

Request request= new AddressRequest ();

what you're doing is saying this Request is an AddressRequest, but by calling it a Request you are unable to access the method for AddressRequest.

A quick solution would be to Safe Cast -> If you're sure that you're dealing with and AddressRequest, then cast request as

(AddressRequest) request.setUserId("11");

Upvotes: 1

Related Questions