-1

I have two 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 an 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 one of the functions I'm getting an a ExpressionA (I have ExpressionB, ExpressionC etc) and I what to cast Expression to what ever I will get from the user.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Sefi Erlich
  • 161
  • 10
  • 1
    If I were you, I'd make `Expression` an interface and implement it in different ways. Then you can do what you're asking. – noMAD May 14 '15 at 22:15

1 Answers1

0

You can not cast a super class to a sub class.

By using a cast you're essentially telling the compiler "trust me. I'm a professional, I know what I'm doing and I know that although you can't guarantee it, I'm telling you that this animal variable is definitely going to be a dog."

Since the animal isn't actually a dog (it's an animal, you could do Animal animal = new Dog(); and it'd be a dog) the VM throws an exception at runtime because you've violated that trust (you told the compiler everything would be ok and it's not!)

The compiler is a bit smarter than just blindly accepting everything, if you try and cast objects in different inheritence hierarchies (cast a Dog to a String for example) then the compiler will throw it back at you because it knows that could never possibly work.

Because you're essentially just stopping the compiler from complaining, every time you cast it's important to check that you won't cause a ClassCastException by using instanceof in an if statement (or something to that effect.)

This has been answered here.

Community
  • 1
  • 1
Forseth11
  • 1,418
  • 1
  • 12
  • 21