The code for a class called “TwoNums” begins as follows: public class TwoNums
{
private int a;
private static int b; Suppose the class also contains the following public methods:
(1) A method called “setA”. It returns nothing, takes a single integer parameter and
places that parameter value into the variable “a”.
(2) A method called “setB”. It returns nothing, takes a single integer parameter and
places that parameter value into the variable “b”.
(3) A method called “getSum”. It takes no parameters and all it does is return the
sum of variables “a” and “b”.Suppose we create “object1” and “object2”, two instances of “TwoNums”, and then the
following code is executed: object1.setA(1);
object1.setB(2);
object2.setA(2);
object2.setB(1);
int sum = object1.getSum() + object2.getSum();the value in “sum” will be:a) 6
b) 5
c) 4
d) 3
能告诉为什么吗?
{
private int a;
private static int b; Suppose the class also contains the following public methods:
(1) A method called “setA”. It returns nothing, takes a single integer parameter and
places that parameter value into the variable “a”.
(2) A method called “setB”. It returns nothing, takes a single integer parameter and
places that parameter value into the variable “b”.
(3) A method called “getSum”. It takes no parameters and all it does is return the
sum of variables “a” and “b”.Suppose we create “object1” and “object2”, two instances of “TwoNums”, and then the
following code is executed: object1.setA(1);
object1.setB(2);
object2.setA(2);
object2.setB(1);
int sum = object1.getSum() + object2.getSum();the value in “sum” will be:a) 6
b) 5
c) 4
d) 3
能告诉为什么吗?
a is a instance varible every instance hold it's value.b is a class varible it is shared by every instance.first b is set value 2 by instance object1 but it is alert 1 by another instance object2.finally instance object1 and object2 share 1 the value of b.
object1.getSum()=1+1=2;
object2.getSum()=2+1=3;
object1.setA(1);object1.setB(2);
这个时候,object1的a的值为1,b的值为2,而object2的a还没有赋值,但是由于b是公用的,所以b已经赋值了,值为2。
object2.setA(2);object2.setB(1);
这个时候,你再给object2的a赋了值2,再给object2的b赋值为1,此时,object1中的值也相应改变成1。
所以最终,object1的a是1,b是1,object2的a是2,b还是1。
int sum = object1.getSum() + object2.getSum();
sum = 1 + 1 + 2 + 1 = 5
object1 object2分别是类TwoNums的对象,所以
object1.setA(1); a=1
object1.setB(2); static b=2object2.setA(2); a=2
object2.setB(1); static b=1 因为b为全局变量,object2可以直接修改b的值,最终b=1;int sum = object1.getSum() + object2.getSum()=1+1+2+1=5
变量b的修饰符是static,static的含义是此类对象公用同一个值,这个值存在静态去,任何一个此类的实例对他进行修改了以后,其他的实例中b的值也将进行改变
所以在object2.setB(1);
代码执行以后object1和object2中b的值都变成了1
这样lz你明白了吗?