'What kind of casting is this? (from Y to X)
public class X{
public void move(){}
}
public interface Y{
abstract void move();
}
public class A extends X implements Y{
}
//in the main function
public static void main(String[] args){
Y eg=new A(); //line 1
X eg2=(X)eg; //line 2
}
What kind of casting would this be from interface Y to class X? Is it a downcasting or upcasting or neither of both?
If it is a upcasting, why do we need an explicit cast in line 2? I tried without an explicit cast and an error was thrown.
Solution 1:[1]
It does not have name, as far as I know. It is generally unsafe, and makes no sense.
Your inheritance tree is below, X and Y are not related with each other. Your attempt will be a result in ClassCastException which occurs an invalid cast.
Object (more accurately, java.lang.Object) is the top of inheritance tree. since X and Y does not extends anything, they inherit from Object implicitly.
Object
/ \
X Y
\ /
A
Solution 2:[2]
I think it's an upcasting too.
You have X that's is a regular class with move() method. You have Y that's is an abstract class, thus cannot be instantiated. You have A class that extends from X, then it inherit the X method. With this, from A you inherit the move() method from X class. You can add "implements Y" to say that you need to code your move function() but this has no real effect since the A class already has the move() method.
In the code in main you are:
Y eg=new A();
You create an A class and assign it to an Y variable. You can do. What you clearly couldn't do it's Y eg = new Y(); since Y cannot be instantiated. This Y knows it has the move() method, but doesn't know it's implementation. Since A has the implementation, you could do this and do Y.move() without issue.
X eg2=(X)eg;
In this case is an upcasting from A->X, since A is the child of X. Upcasting by definition is the typecasting of a child object to a parent object.
Hope you find this useful.
Regards.
Solution 3:[3]
Line Y eg=new A(); does not make the instance to be of type Y. It's always instance of A. You are just assigning it to be referenced by type Y, Y being a super type.
Then in X eg2=(X)eg; you are casting type A to type X & NOT Y to X. This is clearly upcasting.
The explicit casting is needed to remove ambiguity because X & Y are at same level and instance of A can be referenced by both X & Y type.
This link may be helpful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user-id-14900042 |
| Solution 2 | Bandolero |
| Solution 3 |
