简体   繁体   English

将对象向下转换为 java 中的引用

[英]Downcasting Objects to references in java

I am working on an assignment and don't understand downcasting.我正在处理一项任务,但不理解向下转换。 For example, class Reference.java and I'm in a method that passes an object in. If that object is of type (not sure if that is the right word) then create a new Reference object. For example, class Reference.java and I'm in a method that passes an object in. If that object is of type (not sure if that is the right word) then create a new Reference object. This is what I have right now but it doesn't work.这是我现在拥有的,但它不起作用。

public method(Object obj){
     if( obj instanceof Reference){
          Object obj = new Reference();
     }
}

Now the constructor for Reference.java needs two parameters and I also don't understand how in the world this would work when downcasting.现在 Reference.java 的构造函数需要两个参数,我也不明白在向下转换时这将如何工作。

Object obj = new Reference();

This is an upcasting scenario.这是一个向上的场景。


If you want downcasting, then it will be,如果你想要向下转换,那么它将是,

Reference ref = (Reference) obj;

When it works/when it is possible,当它起作用时/当它可能时,

  • Suppose, you create an Object class instance using Reference class (child class reference)假设您使用参考class(子 ZA2F2ED4F8EBC2CBB14C21A29DZ40 参考)创建了一个Object class 实例
Object obj = new Reference();

This is an upcasting.这是一种上调。 And you can do that,你可以这样做,

  • In this case, you can downcast without any ClassCastException在这种情况下,您可以在没有任何ClassCastException的情况下进行向下转换
Reference ref = (Reference) obj;
  • But when it is not clear to you, is it Cast safe or not?但是,当您不清楚时,Cast 是否安全? This time instanceof helps you.这次instanceof可以帮助你。 So the full working code should be-所以完整的工作代码应该是 -
class Reference extends Object{ //not necessary extends Object class, but for 
                                //clearification
  ...

  public static void method(Object obj){
    if(obj instanceof Reference){
      Reference ref = (Reference) obj;
    }
  }
}

In the main method,在主要方法中,

public static void main (String [] args) {  
    Object _obj = new Reference();  
    Reference.method(_obj);  
    //downcast successfull
}  

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

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