简体   繁体   English

在这种情况下,铸造如何工作?

[英]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. 现在,如果我继续将cast2转换为example 1。

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

What will a.getA() return? a.getA()将返回什么?

As a further question from that, if example2 looked like this.. 进一步的问题是,example2是否看起来像这样。

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? a.getA()将返回什么? What happens here, and more importantly why does it happen? 这里会发生什么,更重要的是为什么会发生?

What will a.getA() return? a.getA()将返回什么?

will execute the getA() method of example2 ie 10. 将执行example2的getA()方法,即10。

Even in your second case, it will return 10. 即使在第二种情况下,它也会返回10。

Reason here is method overriding 原因是方法覆盖

Its getting decided during runtime, which getA() method is getting called. 它在运行时决定,哪个getA()方法被调用。
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. 由于您正在创建Example2的对象,因此在两种情况下都将调用Example2的getA(),它会覆盖Example1的getA()方法。

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. 您可以将Example2的对象强制转换为Example1,因为它是父类,但不会改变该对象实际上是Example2的事实。

What would a.getA() return? a.getA()将返回什么?

Will give you the result from example2 , since your instantiated using the class example2 将为您提供example2的结果,因为您是使用class example2 实例化

What happens here 这里发生什么

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

. You are creating an instance of type example1 witn of implementation example2 . 您正在创建类型为example1的实例,其中实例为实现example2 And casting to example1 . 并转换为example1

Casting shows the use of an object of one type in place of another type. 投射显示使用一种类型的object代替另一种类型的object That's it. 而已。 It won't magically convert the instantiated object to casted. 它不会神奇地将实例化的对象转换为强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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