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.
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,
Object obj = new Reference();
This is an upcasting. And you can do that,
Reference ref = (Reference) obj;
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
}