Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Getter methods -- I don't get how to do it properly Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getter methods -- I don Watch "Getter methods -- I don New topic
Author

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

Jeremy Graham
Greenhorn

Joined: Feb 14, 2011
Posts: 14
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

Joined: Jan 10, 2002
Posts: 61449
    
  67

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Steven Barnacle
Greenhorn

Joined: Feb 17, 2012
Posts: 11
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

Joined: Nov 20, 2011
Posts: 144

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.


MySQL Blog
http://mysqlearner.blogspot.com/
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8043
    
  22

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


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
Don't get me started about those stupid light bulbs.
 
subject: Getter methods -- I don't get how to do it properly