public class MyListFragment extends ListFragment {...}
ListFragment listFragment = new MyListFragment();
ListFragment listFragment = (ListFragment) new MyListFragment();
Both lines don't compile with "Cannot cast from MyListFragment to ListFragment".
What you are trying to do is definitely valid, so there must be something outside the code you describe which is causing the problem. The following code compiles.
class A {
}
class B extends A {
}
private void test() {
B b = new B();
A a = b;
A a2 = (A)b;
A a3 = new B();
A a4 = (A)new B();
}
Most likely you have a bad import, two classes with the same name and you have imported one from the wrong package.
Both are valid
ListFragment listFragment = (ListFragment) new MyListFragment();
ListFragment listFragment =new MyListFragment();
As far as OOPS is concerned check this example.
class SuperClass {}
class SubClass extends SuperClass {
public static void main(String[] x) {
SubClass sub = (SubClass) new SuperClass(); //1. ClassCastException
SuperClass sup = (SuperClass) new SubClass();
SubClass sub1 = (SubClass) sup; //2. ok, why?
}
}
Because Compiler checks for only type and JVM checks for value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With