javac#oop

Why not just declare Object class for all objects?


I just came across this amazing tutorial video about Java and I found out that Object class is the super class of all classes behind the scenes. So that easily deals with the problem of having multiple data types in the arraylist by simply declaring the Object class when dealing with the list itself.

My question is this : Why not just declare Object object = new SubObjectClass(); for all objects?

Is this because of some sort of performance inefficiency or memory issue that I have yet to come across? I found another question but I didn't see anyone explain why NOT just have Object class declaration?

I understand why it is there. I apologize if this is a basic question.


Solution

  • You can diclare List of Objects like you said :

    List<Object> list = new ArrayList<Object>();
    

    Which will be universal list of 'Objects' can store any kind of Object.

    But the problem arises when we try to retrive item from such list we will need to cast the retrieved object to the specific Object type. In order to process it further.

    We will not sure which object going to get out of list.