I have a class. I made an object. Is it ok to have a class method that returns an class variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I have a class. I made an object. Is it ok to have a class method that returns an class variable?

public class dog{ string name = "Puppy"; public void dogName(){ return name; } } //this class may have mistakes, but that is not the point.

14th Apr 2020, 6:08 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
4 Answers
+ 2
💜 Alex Tușinean 🍇 It is a good practice to declare your instance variables as private and access them through public getter methods. This way you achieve data hiding and your class is well encapsulated.
14th Apr 2020, 6:26 PM
Avinesh
Avinesh - avatar
+ 3
Hi 💜 Alex Tușinean 🍇 this sounds similar to a getter method. You use the setter method to modify the instance variable and use a getter method to retrieve that value. Yes it is pretty much possible and is used frequently.
14th Apr 2020, 6:16 PM
Avinesh
Avinesh - avatar
+ 2
Avinesh I did that in one of my project, but my teacher told me about classes protection and I've been wondering, if I can't change class variables just by calling them, what if I make a function for that, so I didn't knew if what I did was good or bad.
14th Apr 2020, 6:20 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 1
yes it's possible,(it's the single way to get the value of this variable if it's private!) you defined a getter, but as it returns a string, you should replace void by string public string dogName() { ...
14th Apr 2020, 6:21 PM
John Robotane
John Robotane - avatar