Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Array Initializer Doubt - Bert please explain..

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Please help me out in understanding the following code :


Why is there a type mismatch while converting from Pizza[] to Object ? Also let me know whether Object[] is-a Object?
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

The problem is that when you initialize a variable, the type of the init value must match the type of the variable.
Here, you have an Object type variable named "objects2" and you have a Pizza[] init value. Types don't match.

Arrays are extensions of the Object class. It is then possible to affect an array to an Object variable. The following code is valid:

Object[] objectsTab = {new Pizza(), new Pizza()};
Object obj = objectsTab;

I guess the difference is that during initialization, the JVM will allocated memory space to store the init value. I think that's why types must match, so that the JVM will have necessary information to allocate enough memory.

Sebastien
 
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

It the above code the compiler cannot determine the type of array to be cerated. It can be Pizza[] or Object[]. So statement like this is illegal.

The following code compiles without error.

[ August 25, 2005: Message edited by: Vlado Zajac ]
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic