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
能告诉为什么吗?

解决方案 »

  1.   

    the answer is: b
    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;
      

  2.   

    a和b的作用范围是不同的,a的话是一个实例一个a,也就是说,object1与object2的a是两个不同的a,不会串值,而b是全局范围的变量,也就是说,object1与object2的b是同一个b,只要一个改了就会影响另外一个的。
    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
      

  3.   

    类 TwoNums 有两个属性 int a ,b; 和一个方法int getSum()=a+b;
    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          
      

  4.   

    static的属性,是类的属性,称为全局属性或者静态属性,所有类的对象都能共享这个变量,是所有类的公共属性,在内存的全局数据区,而不在堆的对象数据区,换句不太确当的话说,不管哪个对象修改了这个static属性,所有对象的static 属性 全都跟着变化
      

  5.   

    a的值没有什么特别的,你每次new出来的新的对象设置进去是多少就是多少
    变量b的修饰符是static,static的含义是此类对象公用同一个值,这个值存在静态去,任何一个此类的实例对他进行修改了以后,其他的实例中b的值也将进行改变
    所以在object2.setB(1);
    代码执行以后object1和object2中b的值都变成了1
    这样lz你明白了吗?