Can anyone explain this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone explain this

Class A{ private int a ; Public void age (int a) { Sout("your age is :" + (2021-a)) ; } Public class main{ P. S. V. M(S[] args) { A d=new A() ; d.age(12); Generally we can't access private members but here instead of using get and set methods I have passed through the argument now the code is working what's the use of private Why it's not popping an error?

25th Mar 2021, 3:11 AM
kreddyt
kreddyt - avatar
4 Answers
+ 4
In the class A, the method age() has a parameter named a of type int. Since you're doing '2021 - a' inside the method, the parameter is being subtracted and not the instance variable 'a' present in the class because the variable 'a' is present in the scope of the method as a parameter. In fact, the instance variable is not even used once throughout the code. Even if you were to change the parameter variable of the method, the code would still work (assuming 'a' was initialized) because you're not directly accessing the private instance variable a but using a public method that has access to the private member. Edit : Here's a code for better understanding. https://code.sololearn.com/cqylt8Iz0SKz/?ref=app
25th Mar 2021, 3:25 AM
Soumik
Soumik - avatar
+ 1
D_Stark yeah sout is the short form of printing line and yeah I've just given the overview
25th Mar 2021, 8:31 AM
kreddyt
kreddyt - avatar
0
// more readable class A { private int a; void age (int a) { System.out.println("your year of birth is: " +(2021-a) ); } } public class Main { public static void main(String[] args) { A d = new A(); d.age(12); } }
25th Mar 2021, 10:42 AM
zemiak
- 2
This doesn't look like a java code as your using cout. Also when refrencing a instance variable inside a method and your parameter has the same name you should use this.a = a
25th Mar 2021, 8:30 AM
D_Stark
D_Stark - avatar