short s=1;
s=s+1;
自然是编译不通过的 提示损失精度
那么
short s=1;
s+=1;
为什么能编译通过那?
还有一个问题
public class TestTwo{
private int court;
public static void main(String [] as){
TestTwo e = new TestTwo(99);
System.out.println(e.court); //这里
}
TestTwo(int temp){
court=temp;
}
}
注释部分
我认为它是在静态方法中调用了没静态的变量啊 为什么调试通过了那?
新手莫怪
s=s+1;
自然是编译不通过的 提示损失精度
那么
short s=1;
s+=1;
为什么能编译通过那?
还有一个问题
public class TestTwo{
private int court;
public static void main(String [] as){
TestTwo e = new TestTwo(99);
System.out.println(e.court); //这里
}
TestTwo(int temp){
court=temp;
}
}
注释部分
我认为它是在静态方法中调用了没静态的变量啊 为什么调试通过了那?
新手莫怪
short s=1;
s=(short)(s+1);
short s2=1;
int a =s2+1; 2.调用对象的属性,当然可以调用了.
E1 op= E2 完全等价于:E1 = (T )((E1) op (E2)),其中:T是E1的类型。
所以s+=1;能通过编译。2。你是在一个静态方法中new 出了本类的实例,所以能访问本类的私有方法,并能通过编译,
而不是在静态方法中调用了本类的非静态属性。
如果要在本类中调用非静态属性可以用关键字 this,this关键字就不能在静态方法中用。
The compound assignment operator += lets you add to the value of b, without putting in an explicit cast. In fact, +=,-=,* = , and /= will all put in an implicit cast.
应该能看明白吧,
2.这个是static问题:
A static method can't access an instance variable directly.e.court//Access instance variables using e
//In other words, the court is being invoked on a specific TestTwo object on the heap.
而s+=1的意思与s = s+1不同,s=s+1这句先执行s+1然后把结果赋给s,由于1为int类型,所以s+1的返回值是int,编译器自动进行了隐式类型转换
所以将一个int类型赋给short就会出错,而s+=1不同由于是+=操作符,在解析时候s+=1就等价于s = (short)(s+1),翻番来讲就是
s+=1 <=> s = (s的类型)(s+1)
2,由于你是在TestTwo()方法中调用的court变量,所以并不是在静态方法中调用非静态变量,如果直接在main()方法中对court赋值就会出错。
xyt?不是所有人都这样,教主英语不错吧。
s=s+1; 这里的前一个s就是一个int类型的,而s+1是short类型.这里写肯定是错的.应该是这样s=(short)(s+1); 就没错了.
而
short s = 1;
s += 1;的意思9L的高手已经说的很明白了.我就不再说了.这样写是对的
其它的我就不说了...呵呵..
1,隐式类型转换可以从小到大自动转,即byte->short->int->long如果反过来会丢失精度,必须进行显示类型转换
而s+=1的意思与s = s+1不同,s=s+1这句先执行s+1然后把结果赋给s,由于1为int类型,所以s+1的返回值是int,编译器自动进行了隐式类型转换
所以将一个int类型赋给short就会出错,而s+=1不同由于是+=操作符,在解析时候s+=1就等价于s = (short)(s+1),翻番来讲就是
s+=1 <=> s = (s的类型)(s+1)
2,new关键字就是说明实例化了一个非静态变量。