I find it easier to ask this question through a code example.
class Parent {}
class Child : Parent {}
...
...
Child firstChild = new Child();
Child secondChild = new Child();
Parent firstParent = (Parent)firstChild;
Parent secondParent = (Parent)secondChild;
If I wasn't privy to the above assignments, how would I determine if firstParent
was created from the instance firstChild
without accessing/comparing their fields or properties?
'No', it is an instance of the Child class, not of the Parent.
Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....
No, you can not do. This is because any instance of ClassB is also an instance of ClassA but vice versa is not true. Additionally if above statement is not clear, Unless there's a good reason, it is better to avoid the situation where parent class is dependent on child class. Save this answer.
The instanceof operator. It returns true if obj belongs to the Class or a class inheriting from it. Please note that arr also belongs to the Object class.
Well, firstParent
is not created (there is no "new" keyword being used) but cast from the firstChild
:
Parent firstParent = (Parent)firstChild;
To test use Object.ReferenceEquals
(i.e. firstParent
and firstChild
are just the same instance)
if (Object.ReferenceEquals(firstParent, firstChild)) { ... }
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