• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Chapter5 Review Question #19 (Java OCA 8 Programmer I Study Guide, Sybex)

 
Nil. Hatamova
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. There is a question in Ch5 . Which of the following statements can be inserted in the blank so that the code will
compile successfully? (Choose all that apply)



A. new Cobra()
B. new GardenSnake()
C. new Snake()
D. new Object()
E. new String("Snake")
F. null


The answer is A C F. I understand why A and F is true. But why C is correct? What is difference between B and C?
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nil. Hatamova wrote:The answer is A C F. I understand why A and F is true. But why C is correct? What is difference between B and C?

In order to successfully compile the SnakeHandler class, you'll need a valid argument (parameter) for the setSnake() method. If you have a look at this method, you'll notice that the type of the parameter of this method is Snake. So every instance of a class which passes the "IS-A Snake" check will result in a compilation without errors.

The first important thing to notice: all classes used in this code snippet are concrete (non-abstract) classes, so they can be instantiated using the new operator. Now let's have a look at all the different options:
A. Cobra extends Snake and therefore Cobra IS-A Snake => new Cobra() is a correct option
B. GardenSnake does not extend Snake, so although its name suggests it's a Snake, GardenSnake IS-NOT-A Snake => new GardenSnake() will result in a compiler error and thus is an incorrect option
C. Snake itself is definitely a Snake => new Snake() is a correct option
D. Snake extends Object, but Object does not extend Snake, so Object IS-NOT-A Snake => new Object() will result in a compiler error and thus is an incorrect option
E. String is completely unrelated with Snake, so String IS-NOT-A Snake => new String("Snake") will result in a compiler error and thus is an incorrect option
F. null is always a valid value for a reference variable (regardless of the type of the variable) and therefore null is a correct option too (note: null is an invalid value for a primitive variable)

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic