Search code examples
javadowncast

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. 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.


Solution

  • 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)
    Object obj = new Reference();
    

    This is an upcasting. And you can do that,

    • In this case, you can downcast without any ClassCastException
    Reference ref = (Reference) obj;
    
    • But when it is not clear to you, is it Cast safe or not? This time instanceof helps you. 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
    }