Home > other >  What kind of casting is this? (from Y to X)
What kind of casting is this? (from Y to X)

Time:05-04

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();
    X eg2=(X)eg;
}

What kind of casting would this be from interface Y to class X? Is it a downcasting or upcasting or neither of both?

CodePudding user response:

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

CodePudding user response:

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.

This link may be helpful.

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related