• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Jeremy Graham
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
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64620
86
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.
 
Steven Barnacle
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;
}
 
Zeeshan Sheikh
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.
 
Winston Gutkowski
Bartender
Pie
Posts: 10091
56
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