[英]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,当它起作用时/当它可能时,
Object obj = new Reference();
This is an upcasting.这是一种上调。 And you can do that,你可以这样做,
Reference ref = (Reference) obj;
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.