开发者

Why toBinaryString is not an instance method in Integer class?

开发者 https://www.devze.com 2023-03-20 04:27 出处:网络
A simple design question. Sample code: Integer int1 = new Integer(20); System.out.println(Integer.toBinaryString(int1));

A simple design question.

Sample code:

    Integer int1 = new Integer(20);     
    System.out.println(Integer.toBinaryString(int1));

Why JDK design is not something like the following? so, toBinaryString function returns the the desired result?

    System.out.println(int1.toBinaryString());

Aside for wide usabili开发者_如何学编程ty of a static function, what are the other reasons for this design approach? Are they using any particular design pattern? If it is then, which pattern?


This is because you can't have two methods with the same name, one static and one instance. Having two different method names for the same functionality again would have been confusing.

Putting in a static method seemed more logical since in that case you wouldn't have to "wrap" an int into an Integer before getting its binary representation and it serves both the purposes (binary string for int and for Integer).


Your sample code creates an instance of Integer and then unboxes it. There's no need for that:

int int1 = 20;
String binary = Integer.toBinaryString(int1);

If it were an instance method, you'd be forced to create an instance of Integer solely to convert an int to its binary representation, which would be annoying.

In other words: to avoid creating objects unnecessarily.


Back when this method was added, in JDK1.0.2, there was no autoboxing, and JVMs were much slower than now. I imagine that having this static method allowed converting both an int and an Integer to a binary string easily, and without having to create a new Integer instance just for the conversion of an int to binary.


int, char, double ... these are default datatype, these are not the object. Method should be part of an Object not datatype.

Such static method more efficient than instance method.

0

精彩评论

暂无评论...
验证码 换一张
取 消