Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling Arg-Constructor...

 
Rekha Anand
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Warm Regards to All Java Ranchers...

Please have a look at the following program...

public class Test7{
public Test7(){
this(4);
}
public Test7(short var){ // Line-1
System.out.println(var);
}
public static void main(String[] args){
Test7 t7 = new Test7();
}
}


This code gives compile time error. The problem is with the constructor call
this(4);

If I change the data type in Line-1 from short to int, the code compiles fine. Why am I getting this error although 4 lies in the range of short type..?

Thanks..
Rekha
 
Ravikanth kolli
Ranch Hand
Posts: 179
Chrome Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Rekha Anand ,
All the integer values in java are by default considered as int according to the java language specification.

So when you call a constructor which accepts an int value (4) as a short it gives an error. Since int is much bigger and there might be a loss of precision.

but even when you typecast (4) to short something like ((short)4) then it is going to work fine because you are explicitly telling the compiler to consider the value (4) to be of type short.

hope this helps
 
Rekha Anand
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!! It helped.

Rekha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic