Say I have a Class called ParentClass and a Class called ChildClass
The ParentClass is abstract and the ChildClass extends the ParentClass per Java terminology. Furthermore, the ParentClass has a constructor which takes an int as a parameter. Now in another class I want to instantiate the ChildClass. I have tried the two below ways:
ChildClass obj1 = new ChildClass(5)ParentClass obj2 = new ChildClass(5)Java allows me to use any of the two above ways. My question is, is there actually any difference? Can I use the two, interchangeably if I want to ?
Both work, and both create the same object in memory. But only the first one will allow you to use ChildClass additional specific properties or methods the ParentClass doesn't know about.
Example :
abstract class ParentClass{
...
}
class ChildClass extends ParentClass {
public void someChildMethod(){ ... }
...
}
...
ChildClass obj1 = new ChildClass(5);
ParentClass obj2 = new ChildClass(5);
obj1.someChildMethod(); // ok
obj2.someChildMethod(); // compilation error
((ChildClass)obj2).someChildMethod(); // ok
So, use the second instantiation method only if you're sure you'll never need the specific child methods or properties, if any.
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