-3

当我使用 a=x, b=y 时,结果是 15。但是当我使用 x=a,y=b 时,结果是 0。你能解释一下为什么吗?

public class Test {
        int a , b;

    Test(int x, int y) {    

         a=x;

         b=y;

    }

    int sr() {

        return a*b;
    }

    public static void main (String args[]){

        Test t=new Test(5,3);

        System.out.println(t.sr());
    }

}
4

6 回答 6

4
a=x;

b=y;

will set the instance attributes a & b values with the passed values x and y. so when you create an instance using :

Test t=new Test(5,3);

a and b will be have values 5 & 3 respectively. Hence calling method t.sr will return

a*b = 5*3 = 15;

On the other hand if u use:

x = a;

y = b;

local variables x and y will be set to with the default values of a and b i.e. 0. Also a and b will hold defualt values as 0 as no other value is set. So when u do

 Test t=new Test(5,3);

as a & b have values 0 so calling method t.sr will return

a*b = 0*0 = 0;
于 2013-10-07T06:32:52.923 回答
3

int 字段的默认值为 0。因此,如果您不为它们分配值,则它们为 0。请参阅:http ://www.javapractices.com/topic/TopicAction.do?Id=14

于 2013-10-07T06:29:52.487 回答
1

In the constructor you are passing the value of x and y and storing it in a and b respectivey. Now when you call method a and b has got values so it returns the value of a*b. Also a and b are class variables so it has got default values i.e a=0,b=0; Now in the second case x=a,y=b. you are storing the values of a and b respectivey in x and y.As you are not storing the any values in a and b and again you are calling sr method so it only returns value of a and b i.e 0*0 so you get 0 as output

于 2013-10-07T06:33:01.587 回答
1

when you use x= a, y=b

you are not assigning values to a and b which was used in sr().

Since there are instance variable they will be assigned default value 0 and hence result is 0

于 2013-10-07T06:33:06.393 回答
1

when you use x=a, y=b x and y are local variables. They are discard as soon as that block(constructor) get executed. But a, b are instance variables. They exist until you have the instance from the class. Default value for int instances is 0; since you are not changing those values you always get 0

于 2013-10-07T06:34:18.773 回答
0

In the scope of the constructor, x and y are local variables.

If you do:

x = a;
y = b;

The member variables a and b are never initialized in your constructor. So doing a a * b will yield 0 as the default values for a and b is 0.

And really, it makes no sense to do x = a and y = b.

于 2013-10-07T06:33:59.280 回答