Skip to main content

Parent class and child class example.

2 replies [Last post]
Joined: 2009-04-26

So, in the operators tutorial there is an example of how you would use the instanceof operator.

Now, the code used caught my eye:
class InstanceofDemo {
public static void main(String[] args) {

Parent obj1 = new Parent();
Parent obj2 = new Child();

System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));

class Parent{}
class Child extends Parent implements MyInterface{}
interface MyInterface{}

As you can see when it defines obj2 it first starts obj2 as a Parent but then says it is a new instance of Child. The code works fine and everything and it's definitely not an error.

However, I am just wondering why would you write the code like this. Is it for clarification?
I tried omitting the Parent with Child and the results were the same... so, why declare it like this?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2009-05-27

The code does not start "obj2 as a Parent"; it created a Child and then assigns it to obj2, which is declared to be of type Parent. This is legal because Child is a subclass of Parent. In this case obj2 was declared to be a Parent presumably to show that instanceof applies to the actual type of the obj2, not the declared type.

Joined: 2012-05-14

thank you kathryn, it solved my problem :D