Typecasting an object from parent class to child
Asked Answered
B

5

23

I have a misunderstanding about typecasting in Java language. The problem is ClassCastException. For example, in this code, assuming Animal is the parent class of the Dog class,

Animal animal = new Animal();
Dog dog = (Dog) animal;

throws ClassCastException after execution. However, while studying android packages, I found an example about typecasting which should throw a ClassCastException, considering that java example.

EditText editText = (EditText) findViewById(R.id.edit_message);

In this code, findViewById method returns a View class object, which is one of the superclasses of EditText class.(from android.view.View to android.widget.EditText) The code runs fine. Could anyone explain if I made a mistake or how this happens?

Thanks in advance.

Beautify answered 7/8, 2014 at 22:4 Comment(3)
If you know how tag this question with a polymorphism tag, you know how to search the concept on this site or elsewhere. Seriously, this is too basic. Search before you post.Virelay
The question is not about polymorphism mechanism, I know the example does consist of polymorphism. The real question is about the android implementation. I know why it gives the exception and I ask for clarification of android code.Beautify
There is no "Android implementation". Treating an object like its ancestral parent is the heart of polymorphism, which is key aspect of OOP and therefore Java (and therefore Android). My comment tried to tell you, you were too quick to post such a basic question that could have easily been answered performing a simple search in SO or Google (or reading developer.android.com thoroughly)Virelay
C
30

Once you create an object, you can't change its type. That's why you can't cast an Animal to a Dog.

However, if you create an object of a sub-class, you can keep a reference to it in a variable of the super-class type, and later you can cast it to the sub-class type.

This will work :

Animal a = new Dog ();
Dog d = (Dog) a;

In the Android example, you have a layout resource that looks like this :

<EditText
    android:id="@+id/edit_message"
 ..."/>

This definition will cause Android to create an instance of EditText, and therefore you can cast the view returned by findViewById to EditText. You can't cast it to anything else that isn't a super-type of EditText.

Cartomancy answered 7/8, 2014 at 22:6 Comment(4)
OK, I understand how this kind of typecasting works. However, the android example confuses me. If I don't instantiate the object in the subclass, can I cast every super class object to a sub class object like in the android example? I will write a method instead of directly typecasting: "parent class" public Animal foo(){ Animal animal2 = new Animal(); return animal2; } and "sub class" Dog dog = (Dog) animal.foo(); this still gives the exception.Beautify
@Beautify No, in the Android example, Android instantiates the object based on the definitions in the layout xmls. You can only cast it to its correct sub-type.Cartomancy
You should read polymorphism and typecasting in java , there is nothing unusual happening in Android.Hyponasty
@Beautify In this particular case, Android does the instantiation, but you'll encounter this behavior in many object oriented platforms that instantiate objects from definition files.Cartomancy
E
6

Basically you can't cast an instance of a superclass to a subclass because the instance of a subclass is not yet known. Upcasting is a sure way to prevent this exception to happen because we are now dealing polymorphism to our code.

You must instance a subclass first:

Dog dog = new Dog;

We can hide the methods of the class Dog not found to its parent class Animal by casting it to its superclass:

Animal animal = (Animal) dog;

Then you can downcast this back to your subclass Dog because the instance of its subclass is already known:

Dog anotherDog = (Dog) animal;
Eleneeleni answered 7/8, 2014 at 22:14 Comment(0)
I
2

You can try this:

Base obj= new Derived();
Derived obj2= (Derived)obj;

Hope this will help.

Inclusion answered 4/9, 2018 at 6:39 Comment(0)
W
1
public class OverridingConcept {
    public static void main(String[] args) {
        // Up-Casting
        Parent p = new Child();
        Child c = (Child) p;
        c.eat();
    }
}
class Parent {
    void show() {
        System.out.println("Parent.Show");
    }
    void eat() {
        System.out.println("Parent.Eat");
    }
}
class Child extends Parent {
    void show() {
        System.out.println("Child.Show");
    }
    void sing() {
        System.out.println("Child.Sing");
    }
}
Winfrid answered 7/2, 2020 at 18:42 Comment(0)
C
-2

If you want to change the parent to child then use below code.

Animal a= new Animal(); Dog d= Dog.valueof(a);

Cytoplast answered 22/3, 2022 at 12:23 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Zeph
There is no such method valueof() for Dog. This is completely wrong in every respect.Interest

© 2022 - 2024 — McMap. All rights reserved.