Cast parent class to son calls -java -


i have 2 classes:

public class expression {   public expression(){};     public  void submeet_in_expression(double i){};      public  void just_submeet(double double1){};      public   double getvalue(){         return -1;     }; } 

and extends class:

public class expressiona extends expression{     double ans;      public expressiona(){         ans=1;     }     public void submeet_in_expression(double i){         ans= (ans*(math.pow(-1,i)/(2*i+1)));     }     public void just_submeet(double i) {         ans*=i;      }      public double getvalue(){         return ans;     }  } 

in 1 of functions i'm getting expressiona (i have expressionb, expressionc etc) , cast expression ever user.

you can not cast super class sub class.

by using cast you're telling compiler "trust me. i'm professional, know i'm doing , know although can't guarantee it, i'm telling animal variable going dog."

since animal isn't dog (it's animal, animal animal = new dog(); , it'd dog) vm throws exception @ runtime because you've violated trust (you told compiler ok , it's not!)

the compiler bit smarter blindly accepting everything, if try , cast objects in different inheritence hierarchies (cast dog string example) compiler throw @ because knows never possibly work.

because you're stopping compiler complaining, every time cast it's important check won't cause classcastexception using instanceof in if statement (or effect.)

this has been answered here.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -