0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anthony
  • 51
  • 6
  • 4
    `Object obj = new Reference();` should probably be `Reference ref = (Reference) obj;` – Lino Apr 01 '21 at 20:53
  • 4
    You can't declare 2 variables (including parameters) with the same identifier in the same scope. You already have something called `obj` so use another name. – Michael Apr 01 '21 at 20:55

1 Answers1

2
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
}  
Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25