+ 1

Asking about access modifiers in java!

public class Program { public static void main(String[] args) { //James Worker worker1 = new Worker(); worker1.name = "James"; worker1.salary = 200000; //Tom Worker worker2 = new Worker(); worker2.name = "Tom"; worker2.salary = 150000; System.out.println(CalculateTotalSalary(worker1.salary,worker2.salary)); } //complete the function to calculate the total salary static int CalculateTotalSalary(int a, int b){ int sum = a + b; return sum; } } class Worker{ String name; int salary; } If static method cannot access to non-static variables why the //System.out.println(worker1.salary,worker2.salary)" works? //I think worker1.salaray and and worker2.salary are non static variable. Am I wrong , sir?

6th Dec 2021, 2:36 PM
Noname
Noname - avatar
8 Réponses
+ 2
main() can access and use <worker1> and <worker2> because they are local variables. That also mean main() can access and use members of `Worker` instances (<worker1> and <worker2>). For example the 'salary' member. Except if the respective members were defined as private, in which case a getter/setter is usually employed for manipulating the private members' value. So main can access <worker1>.salary and <worker2>.salary. Then when main() invokes CalculateTotalSalary() main() passes the two values as method arguments. CalculateTotalSalary() makes copies of them, sum them up, and return the result.
6th Dec 2021, 3:49 PM
Ipang
+ 1
Ipang that's why they can be accessed into the "CalculateTotal" static method?
6th Dec 2021, 3:08 PM
Noname
Noname - avatar
+ 1
If you want to access non-static variables of a class in a static context then you need an object of that class and have access through that object. Thats the way to access non-static variables are accessed in static method..( you cannot access directly.. ) There you accessing salary by object worker1. Simply 'salary' will error instead of worker1.salary Hope it helps..
6th Dec 2021, 3:25 PM
Jayakrishna 🇮🇳
+ 1
Ipang i see that but salary is not static variable , then Why salary copies can act like statics variables
6th Dec 2021, 3:27 PM
Noname
Noname - avatar
+ 1
Ipang thanks a lot👌
6th Dec 2021, 3:52 PM
Noname
Noname - avatar
+ 1
6th Dec 2021, 3:56 PM
Noname
Noname - avatar
0
<worker1> and <worker2> are local variables, they're accessible. A static method cannot call non static methods. Also, a static method cannot access non static members (variables etc.) defined outside the static method itself. If you defined <worker1> and/or <worker2> outside main(), they will not be accessible inside main() which is a static method. Here they are accessible cause they are defined locally.
6th Dec 2021, 3:02 PM
Ipang
0
The CalculateTotalSalary() only receives copies of <worker1> and <worker2> salary values. main() can call CalculateTotalSalary() because both are defined as static methods ...
6th Dec 2021, 3:13 PM
Ipang