• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assignment  RSS feed

 
bernard adaba
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i was practising a question and had the answer wrong. What is the difference between the operation happening at statement comment //3 and //4. Why does comment //4 compiles and runs fine whiles comment //3 compiles but runs with a ClassCastException.

please find the code below:




interface Inter{}

class Base implements Inter{}

class Derived extends Base{}

public class TestG{

public static void main(String[] args){

Base b = new Base();

Derived d = new Derived();

Inter i = (Base)b; //1

i = (Base)d; //2

Derived bd = (Derived)b; //3

b =(Base)i; //4

}

}



thanks
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you get that exercise from? We don't simply give out such answers

Go through the code, and write down the types of the references, and the types of the objects, and write down what you are casting to what. Then the answer should become obvious.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!