0

im a beginner in java and i study everyday from books . there is a quistion that press my brain so hard for so long , what is usefulness of creating an object and give it an another object refrences ! i saw too many examples of this format .

Cat simon = new Cat();
Animal tiger = simon;
  • 2
    This is called polymorphism: http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and-how-is-it-used – Bogdan Jan 17 '15 at 10:48
  • Also, just for the record, it is customary to name object instances using lowercase / lowerCamelCase names, to avoid confusion with class names. – Michał Szydłowski Jan 17 '15 at 10:57

2 Answers2

0

This can be useful in cases in many different cases (although as a general term this refers to Polymorphism), one I can think of is a Parent array creation. (Parent being the Animal class in this case, which is further extended by Cat).

Animal[] animals = new Animal[] { simon, dog };

You can reference every item in the list simply by using Animal parent type, you don't have to worry about it being further of type Dog or Cat etc.

So suppose you iterate over this and call the sound()/voice() method for each element. If the method is defined in the Parent class (i.e. Animal), you can simple do:

for (Animal animal : animals) {
  System.out.println(animal.voice());
}
nitishagar
  • 9,038
  • 3
  • 28
  • 40
  • 1
    A piece of advice. You should not use generics to explain this particular question as that will raise questions about the lack of covariance for collections. – Bogdan Jan 17 '15 at 10:53
0

The main purpose of an Object reference by itself is to tell Java to keep the Object around. Otherwise, the memory used in that Object will go away (reclaimed by the Garbage Collector). And, with the reference, you can trigger actions on the Animal (like simon.eat() and simon.sleep()). Without the reference, you couldn't do this. Anything you work on in any program must stay around by having some reference to it (like you did above).

The Object reference between Animal and Cat shows that "I can treat Cat, Dog, Elephant, Eagle, Moose, etc. any animal that is an Animal like an Animal." (This is called polymorphism.)

So, an Animal can have actions like eat() and sleep() because all Animals can eat() and sleep(). But, an Eagle can also fly(). So, Eagle has the fly() action defined. And, you wouldn't put the fly() action in Animal because not all Animals can fly().

Danny Daglas
  • 1,501
  • 1
  • 9
  • 9