简体   繁体   中英

How does casting work in this situation?

So let's say I have two classes.

public class example1 {

    private int a;
    private String b;

    public example1(int a, String b) {
        this.a = a;
        this.b = b;
    }

    public int getA() {
        return a;
    }
    public String getB() {
        return b;
    }
} 


public class example2 extends example1 {

    public example2(int a, String b) {
        super(a, b);
    }

    @Override
    public int getA() {
        return 10;
    }
}

Now, if I go ahead and cast example2 to type example 1.

example1 a = (example1) new example2(5, "Hi");

What will a.getA() return?

As a further question from that, if example2 looked like this..

public class example2 extends example1 {

    public example2(int a, String b) {
        super(a, b);
    }
    @Override
    public int getA() {
        return getAModified();
    }
    public int getAModified() {
        return 10;
    }
}

What would a.getA() return? What happens here, and more importantly why does it happen?

What will a.getA() return?

will execute the getA() method of example2 ie 10.

Even in your second case, it will return 10.

Reason here is method overriding

Its getting decided during runtime, which getA() method is getting called.
Since you are creating an object of Example2, hence in both cases the getA() of Example2 is getting called, its overriding the getA() method of Example1.

You are able to cast the object of Example2 to Example1 as it is parent class but it won't change the fact that the object is actually of Example2.

What would a.getA() return?

Will give you the result from example2 , since your instantiated using the class example2

What happens here

example1 a = (example1) new example2(5, "Hi");

. You are creating an instance of type example1 witn of implementation example2 . And casting to example1 .

Casting shows the use of an object of one type in place of another type. That's it. It won't magically convert the instantiated object to casted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM