Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

initialization  RSS feed

 
mark geroso
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code, I'm supposed to initialize White.colorName to white.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16026
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That code will compile without errors, but it does not do what you think it does.

In class White, you are not initializing the member variable colorName that's in class Color. Instead, you have declared and initialized a new member variable colorName in class White. The member variable colorName from class Color isn't visible in class White, because it's private.

So with your code above, if you create a new White object and call getColor() on it, you will get back null instead of a string containing "White" - because the variable colorName in class Color is null.

If you want to set colorName in class Color to "White", there are several things you could do:

1. Call setColor(...) in the constructor of class White.
2. Make colorName in class Color protected instead of private, and initialize it in the constuctor of class White (you'll have to remove the member variable colorName from class White).
 
mark geroso
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem given stated:
The class White inherits from Color, and has its (private) attribute colorName set to White.

I interpreted it to mean the code above. Was I wrong?
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!