开发者

Why method is not called according to data type , if the value needs to be stored in a variable

The following java code will not execute.

class A{

int sqrt(int a)
{
}

fl开发者_运维知识库oat sqrt(int a)
{

}


int a1 = sqrt(a);
float b1= sqrt(b);



}

In interview i was asked by a question that why java compiler does not check the data type and call that method accordingly. What is the reason?


Those methods have the same signature (identifier + parameter list), which is illegal.


The reason the compiler won't allow this is that it is not always possible to infer the desired data type. For example, Java supports "boxing" of native values into objects, so you should be able to do this:

ArrayList<Object> list = new ArrayList<Object>();
list.add(a.sqrt(4));

In code like this, it would be literally impossible for the compiler to figure out whether you wanted to call the method that returns a float or the method that returns an int.


If you have 2 methods with same name and same parameters of same data types then java compiler will not even let you compile the code. It should say that method "sqrt" is already defined. So it's illegal in java.


I asked when i was a beginner in programming. . Let me give the answer myself. It always checks the return type of method and call that method accordingly . In case of

int a1 = sqrt(a);

it will call method whose return type is integer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜