-1

In Java's class hierarchy, can an object be initialized in such a manner?

subclass object = new superclass();

This assumes that both the subclass and superclass have proper constructors, can compile, etc. Is this type of object construction possible?

auxilarus
  • 3
  • 3

1 Answers1

0

No. Only the other way around. When you have an object of a class you can refer to it by a reference of the same class or a parent class and not the reverse. This is probably not related to just Java. Otherwise it wouldn't make sense. Suppose you have

class SuperClass {
    public void method1() {};
}

class SubClass {
    public void method2() {};
}

If you do

  SubClass object = new SuperClass();

and then

  object.method2();

then theoretically it should compile, because the reference is of type SubClass, but the object is of type SuperClass so it won't have such a method.

Ruslan
  • 3,063
  • 1
  • 19
  • 28