Search code examples
javaoopreference-type

Using Object variables to reference new data types/objects


I have had a burning question for a long time now, relating to the Java syntax and why it allows this:

Object object1 = new Integer();

Why can we declare child classes using Object as a reference? Also, let's take a look at this piece of code:

public class Parent{}    
public class Child extends Parent{}

public static void main(String[] args){
   Parent var1 = new Child();                
   Object var2 = new Child();
   Object var3 = new Parent();                
}

All three cases will run, as I have tried this. The question is, does it matter whether I use Object to reference a new object/variable or the actual class name? Also, how does the reference type selected affect the program and code? Does a certain reference type like "Object" take up less memory or make the program more efficient? Thanks in advance


Solution

  • The question is, does it matter whether I use Object to reference a new object/variable or the actual class name?

    Yes, it does. If you use the general interface/class name for your reference it will allow you to use dynamic dispatch, which means to decouple the client code from concrete implementations. Let's say you have Cat and Dog classes which extend Animal class. Both classes overide makeNoise() method. Then you may write a code:

    Animal animal = animalFactory.getAnimal(); 
    animal.makeNoise();
    

    Which is not dependent on a concrete implementation of animal: it may be Dog or Cat whatever you need. The advantage of this approach is that your code is less prone to changes. Less changes -> less bugs. But it is important to mention, that you may only call the methods which are declared in the variable type. So, if your variable is Object type only Object methods are available to be called.