0

Item i1 = new CD();

I don't understand how I can instantiate an object from a class and put it in another class? Please explain what do the classes Item and CD refer to?

Joachim Rohde
  • 5,915
  • 2
  • 29
  • 46
  • `Item i1` defines variable, and allows it to hold reference to objects of type `Item`. `new CD();` creates object of type `CD` and returns reference to it which is assigned to variable `i1`. We can do it when class `CD` is subtype of class/interface `Item`. – Pshemo Mar 15 '20 at 13:09
  • Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. Suppose My Parent Class is like, Class Parent { } Class SubClass{ } Class Main { Parent p; p = new SubClass(); // here is code from this you can call subclass method } – Thakkar Darshan Mar 15 '20 at 13:11
  • You're asking "Why is `Item i1 = new CD();` allowed when `Item` and `CD` are obviously different classes?", yes? – Kevin Anderson Mar 15 '20 at 13:28
  • @KevinAnderson yes sir, and I think I got it from mr Pshemo but i don,t know what is the meaning of "hold reference" ? – Abdullah Morsi Mar 15 '20 at 13:31
  • Maybe this will help: [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172) – Pshemo Mar 15 '20 at 13:54
  • He means "hold [a] reference to...". Or just "refer to...". But even that only make any sense if you understand that variables in Java hold _not_ actual objects, but rather _references_ to objects. – Kevin Anderson Mar 15 '20 at 13:54
  • thank you so much I read it and I understood. – Abdullah Morsi Mar 15 '20 at 14:38

2 Answers2

2

Presumably, CD either extends Item, or, if Item is an interface, CD implements it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Item i1 defines variable, and allows it to hold reference to objects of type Item. new CD(); creates object of type CD and returns reference to it which is assigned to variable i1. We can do it when class CD is subtype of class/interface Item.