Right now I’m trying to implement this interface with an int which represents a binary number.
I know I shouldn’t implementto string(); , but Let’s assume that I need to.
This is what I wrote so far:
public class IPAddressInt implements IPAddress {
private int ipAdress;
public IPAddressInt(int num1,int num2, int num3, int num4){
String n1=Integer.toBinaryString(num1);
String n2=Integer.toBinaryString(num2);
String n3=Integer.toBinaryString(num3);
String n4=Integer.toBinaryString(num4);
String finalString=n1+n2+n3+n4;
this.ipAdress=Integer.parseInt(finalString);
}
public String toString() {
return this.toString();
}
when I’m tring to return this.ipAdress.toString(); or even ipAdress.toString()
the compiler says that it Cannot invoke toString() on the primitive type int,
and when I write only this.toString(); it works. why? I know that an int can be converted to a string, and how come the this works and the whole statement is not? shouldn’t it be the same? will I get what I want anyway?
Thank you.
Calling
this.toString()is just going to blow up – it’s calling the same method recursively, with no exit.The reason you can’t call
toStringdirectly onipAddressis thatintis a primitive type, and you can’t call methods on primitive types.To convert anything to a string, use
String.valueOf(ipAddress). Forintin particular, you could useInteger.toString(ipAddress).It’s not really clear why you’re doing the conversion to a binary string in the first place though… that doesn’t look like a good idea to me. Any reason why you’re not using
(assuming each value is really in the range 0-255).
I highly doubt that the binary representation is really want you want, particularly given the lack of padding, and that you’re then trying to parse it as a decimal number.