java java中子类对象到超类的显式类型转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12843844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:26:32  来源:igfitidea点击:

Explicit Type Conversion of sub class object to super class in java

javacastingtype-conversion

提问by Ankur

Consider below code:

考虑下面的代码:

public class Test{
  public static void main(String str[]){
     B b = new B();
     A a1 = (A)b;//Explicit type conversion
     A a2 = b;
  }
}
class A{}
class B extends A{}

In the above code are the two line:

在上面的代码中有两行:

A a1 = (A)b;//Explicit type conversion
A a2 = b;

Equivalent? If notthen what is the difference between the twoand if yesthen is there any scenario in javawhere we need to explicitly convert a sub class object into a super class object?

相等的?如果不是,那么两者之间有什么区别,如果是,那么在 java中是否有任何场景我们需要将子类对象显式转换为超类对象

回答by Peter Lawrey

The explicit type casting of the reference, not the object) is redundant and some IDEs will suggest you drop it.

引用的显式类型转换,而不是对象)是多余的,一些 IDE 会建议您删除它。

If you do

如果你这样做

A a1 = (A)b;

You can still do

你仍然可以做

B b2 = (B) A;

to cast the reference back to type of B.

将引用转换回 B 类型。

Note: the object is not altered in any way and is always a B

注意:对象没有以任何方式改变,并且始终是一个 B

there is no scenario in java where you would need it?

java中没有你需要它的场景吗?

The only time you need an upcast is in method selection.

您唯一需要向上转换的时间是在方法选择中。

void method(Object o) { }

void method(String s) { }

method("hello");          // calls method(String)
method((Object) "hello"); // calls method(Object)

回答by Amber

Such type conversion is also required for method selection using overloading :

使用重载的方法选择也需要这种类型转换:

package casting;
public class ImplicitCasting {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        A a1 = new B();
        methodA(a);      // methodA called
        methodA((A)b);   // methodA called
        methodA(b);      // methodB called
    }

    public static void methodA(A a) {
        System.out.println("methodA called");
    }

    public static void methodA(B b) {
        System.out.println("methodB called");
    }
}

class A{

}

class B extends A{

}       

回答by Yogendra Singh

They are not equivalent in your example.

它们在您的示例中并不等效。

This becomes importantin other way assignment i.e. from Ato Bwhile your object is still type B

在其他方式分配中变得很重要,即从A到,B而您的对象仍然是类型B

e.g. consider the sequence below:

例如,考虑以下序列:

      A a = b;// will work
      a = (A)b;// will work
      B newB = (B)a; //will work
      B newB = a;  //will fail

回答by Rohit Jain

There is no difference between the two. In fact, you don't needto type cast explicitly from a subclass object to a super class reference. So, the first way is absolutely Redundant.

两者之间没有区别。事实上,您不需要显式输入 cast from a subclass object to a super class reference。所以,第一种方式是绝对的Redundant

From the JLS - Conversion: -

JLS - 转换: -

5.1.5. Widening Reference Conversion

A widening reference conversion exists from any reference type S to any reference type T, provided S is a subtype (§4.10) of T.

Widening reference conversions never require a special action at run-time and therefore never throw an exception at run-time. They consist simply in regarding a reference as having some other type in a manner that can be proved correct at compile time.

5.1.5. 扩大参考转换

存在从任何引用类型 S 到任何引用类型 T 的扩展引用转换,前提是 S 是 T 的子类型(第 4.10 节)。

扩展引用转换在运行时不需要特殊操作,因此在运行时永远不会抛出异常。它们只是将引用视为具有某种其他类型,并且可以在编译时证明其正确。

Explicit type casting is only required at place where it is not obvious that the reference type can store the object. But when you create an object of subclass and make reference of super class point to that object, then compiler never has an problem with that. Since that can always he handled at runtime.

显式类型转换仅在引用类型不明显可以存储object. 但是,当您创建子类的对象并使超类的引用指向该对象时,编译器永远不会有问题。因为他总是可以在运行时处理。

回答by Bhesh Gurung

Equivalent? If not then what is the difference between the two

相等的?如果不是那么两者有什么区别

The only different is that one is implicit while other is explicit (which is not required), The result is equivalent. Note: The casting works on reference to the object, not on the object itself.

唯一不同的是,一个是隐式的,另一个是显式的(这不是必须的),结果是等价的。注意:转换适用于对对象的引用,而不是对象本身。

is there any scenario in java where we need to explicitly convert a sub class object into a super class object?

java中有没有需要将子类对象显式转换为超类对象的场景?

Java supports Liskov substitution principle, so there shouldn't be any scenario like that.

Java 支持Liskov 替换原则,所以不应该有这样的场景。

回答by Manas Srivastava

They are both the same. This is a case of downward typecasting which is automatic.

他们都是一样的。这是一种自动向下类型转换的情况。

A a1 = (A)b;//Explicit type conversion A a2 = b;

A a1 = (A)b;//显式类型转换 A a2 = b;

In both cases type of a1 and a2 is A. So additional characteristics of B is anyway lost.

在这两种情况下,a1 和 a2 的类型都是 A。所以 B 的附加特征无论如何都丢失了。

You will know the difference if you do upward typecasting which is not Automatic. consider following example.

如果您进行非自动的向上类型转换,您就会知道其中的区别。考虑以下示例。

Vehicle v1 = new Car(); //Right . upcasting or implicit casting

车辆 v1 = new Car(); //对 。向上转换或隐式转换

Vehicle v2= new Vehicle();

车辆 v2= new Vehicle();

Car c0 = v1; // Wrong compile time error "Type Mismatch" //Explicit or downcasting is required Car c1 = (Car) v1 // Right. downcasting or explicit casting . v1 has a knowledge of Car due to line 1

汽车 c0 = v1; // 错误的编译时错误 "Type Mismatch" // 需要显式或向下转换 Car c1 = (Car) v1 // 对。向下转换或显式转换。由于第 1 行,v1 具有 Car 的知识

Car c2= (Car) v2; //Wrong Runtime exception ClassCastException because v2 has no knowledge of Car.

汽车c2=(汽车)v2;//错误的运行时异常 ClassCastException 因为 v2 不知道 Car。

Bus b1 = new BMW(); //Wrong compile time error "type mismatch"

总线 b1 = 新 BMW(); //错误的编译时错误“类型不匹配”

Car c3 = new BMW(); //Right. Upcasting or implicit casting

汽车 c3 = 新宝马(); //对。向上转换或隐式转换

Car c4 = (BMW) v1; // Wrong Runtime exception ClassCastexception

汽车 c4 = (宝马) v1; // 错误的运行时异常 ClassCasException

Object o = v1; //v1 can only be upcast to its parent Car c5 = (Car) v1; // v1 can be downcast to Car due to line 1

对象 o = v1; //v1 只能向上转换到它的父 Car c5 = (Car) v1; // 由于第 1 行,v1 可以向下转换为 Car