0
Return function, Getters and Setters
First off, I would like to mention I'm a novice programmer. 1. Why do we need the return function at all? Are values stuck within classes? Thus why do we need access modifiers if each value isn't accessible till we return it? 2. How differs the input using Getters and Setters from just saying static class Vehicle { String color;} public class test { public static void main(String[]args){ Vehicle BatMobile = new Vehicle(); BatMobile.color = "pink"; }}
3 odpowiedzi
+ 14
May be the right time for you now to learn about the oop stuff.
+ 13
1. For data hiding aka encapsulation. You can declare any variable in your class global and public. But then you don't have any control because it can be used everywhere in the code. Imagine you have a bank account. Do you want everyone to have access to your variable amount? Change it to negative e.g.? But someone might be allowed to see, what your amount is, without changing it. Programmatically you could use a get method then, which returns the value of amount, so you can read it.
2. If you allow access by a set method you can e.g. check, if the passed value is correct. Again: encapsulation. Referring to the bank account example: You try to set your amount from 5,000 to 0. But no! You aren't allowed to do that, you can only withdraw 2,000.
Not that good example, but I hope you get the meaning of encapsulation.
+ 1
Thanks a lot. Seems that further tutorial materials introduce encapsulation to me.