what happens when a parent class object takes value of child class object

Viewed 37

I was playing with code, see the comment besides the code, my question is:

Is og of child type or parent type?

public static void main(String[] args)
{
    inherit og = new child();
    og.play();
    ( (child)og).kick((child)og);   //kick is a function in child class wi=hich accepts an object of the child class as parameter
    // gives an error if we remove explicit conversion
     System.out.println(og instanceof child);   //true
     System.out.println(og instanceof inherit);  //true
    System.out.println(og.getClass().getSimpleName());  //child
}
3 Answers

It's of child type, since you have instantiated child in this line

inherit og = new child();

and assigned the new child instance to og.

The object "og" is of the child class. This process is known as polymorphism. Because the "child" class extends the "inherit" class, any commands done to the child class will also call on the parent's ("inherit") constructor.

When you say:

og instanceof child
og instanceof inherit

The reason why both of these say "true" is because you wrote "Inherit og = new Child();". So, the "Child()" causes the constructor in the "Inherit" class to be called. As a result "og" identifies as both of them.

The "child" is also calling the "inherit" constructor. So, both of these are true since both constructors are called. However, in reality the answer is that it's of type "child".

og is of child type or parent type?

As used in the example code, the fragment

inherit og

declares og as a reference to an object of type inherit. That is the type of the expression og. This is a compile-time characteristic of the source code presented. Thus, og is of the parent type.

The code presented also initializes variable og with a reference to an object of class child. For all intents and purposes, that is a run time detail of an execution of the program. It does not change the type of variable og or of the expression og, but it does mean that at run time, evaluation of the cast expression (child) og can be expected to succeed instead of throwing a ClassCastException.

A reference of a type T can refer to an object whose class is a subtype of T. That does not change either the type of the reference or the class of the object -- these are different considerations. I personally try to maintain the distinction by using the word choices you can see in this answer: references have a type, whereas objects have a class.

As a separate matter, please follow standard Java naming conventions. In particular, classes should be named in camel case, with an initial capital letter. Following that and the other standard conventions makes your code much easier for others to read.

Related