简体   繁体   English

继承Java超类和类型转换

[英]Inheriting Java super class and Type Casting

I have two Classes in Java 我有两个Java类

Class A { void method1(){} }
Class B extends A {  void method2(){} }

When I run the following it works fine: 当我运行以下命令时,它工作正常:

Class C {
  public static void main(String [] args){
    A a1  = new A();
    A a2 = new B();
    B b1 = new B();
    ((B)a2).method2();
  }
 }

but why the following does not work ? 但是为什么下面的方法不起作用?

Class C {
  public static void main(String [] args){
    A a1  = new A();
    A a2 = new B();
    B b1 = new B();
    (B)a2.method2();
  }
 }

Thanks 谢谢

You have to call the method after casting. 强制转换后必须调用该方法。 You need brackets around a2 ie 您需要在a2周围加上括号,即

((B)a2).method2();

Like Kabir said, you need to first cast the object before calling a method from another object. 就像Kabir所说的那样,您需要先转换对象,然后再从另一个对象调用方法。

It is because Java reads your second statement as: (B) (a2.method2();) 这是因为Java将第二条语句读取为: (B) (a2.method2();)

So java tries to use method two in the A object a2, but it can't because there is no method2() in that object. 因此,java尝试在A对象a2中使用方法2,但不能这样做,因为该对象中没有method2()

However, when you type cast it (By putting (B) before a2 in parenthesis), it reads it like: 但是,当您键入强制转换时(通过将(B)放在括号中的a2之前),它的读取方式如下:

(Turn a2 into B).method2();

Which runs fine because it is turning a2 into a B, which includes method 2, beforehand. 可以正常运行,因为它先将a2变成了B,其中包括方法2。

In an easy comparison with a math concept, it is like the order of operations on how you calculate values. 与数学概念轻松比较时,就像计算值的操作顺序一样。 You wouldn't say 5 + 5 * 2 = 20 , you would say 5 + 5 * 2 = 15 , because it first calculates 5 * 2 , then adds 5 . 您不会说5 + 5 * 2 = 20 ,而是5 + 5 * 2 = 15 ,因为它首先计算5 * 2 ,然后加5

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

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