Win a copy of Pipeline as Code this week in the Cloud/Virtualization 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Whizlabs test question : Generics

 
Ranch Hand
Posts: 686
Netbeans IDE Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following question is from Whizlabs. I know the answer is "Compiles with warnings, prints some output at runtime"
How can we add Circles into Rectangles??

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

How can we add Circles into Rectangles



We are not adding Circles into rectangle.It is clear at line 16 that c can hold only Rectangle


At run time there is no type safety, means JVM doesn't know that a is type safe for Circle.

Regards
Sunny Mattas
SCJP5

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You created a reference type c which can hold an arrayList of only Rectangle objects. But it is assigned to b, which is a arrayList of Object.So you can add any object, problem will come only when you try to get the object from the List and cast Circle object to Rectangle Object.

You are not assigning c to a, which is Arraylist of type Circle. So c can add a Circle Object.Use of Generic will prevent you adding a Circle object to a ArrayList of type Rectangle.

 
This guy is skipping without a rope. At least, that's what this tiny ad said:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic