This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Getter methods -- I don't get how to do it properly  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure how to properly write a getter method. Here's an example code:



The compiler gives me this error: "cannot return a value from method whose result type is void". So, what's wrong?

Thanks
 
Author and ninkuma
Marshal
Posts: 66536
160
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's saying exactly what it's unhappy about. Your body returns a String, but the signature says it's returning nothing (void). They can't both be right.
 
Greenhorn
Posts: 16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeremy,

In your getter method code the use of void indicates that you are not returning anything

# public void getName() {
# return catName;
# }

Your need to amend void to String

public string getName() {
return catName;
}
 
Ranch Hand
Posts: 144
Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can not use return keyword in method & void signature at the same time. void means no return type. Getter method should return a value & change it to String as instance variable catName is of type String.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Steven Barnacle wrote:Your need to amend void to String

public string getName() {...


Hmmm. Spot the deliberate mistake?

Zeeshan Sheikh wrote:You can not use return keyword in method & void signature at the same time.


Sure you can:Silly example I know, but...

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!