请分别写出E类中代码1和代码2的输出结果。 class A{ double f(double x,double y){ return x+y;} } class B extends A{ double f(int x,int y){ return x*y;} } public E{ public static void main(String[] args){ B b=new B(); System.out.println(b.f(3,5));//代码1 System.out.println(b.f(3.0,5.0));//代码2 } }
时间: 2024-04-28 16:26:25 浏览: 24
代码1的输出结果为 15.0,代码2的输出结果为 8.0。
这是因为在类 B 中,方法 f(int x, int y) 重写了超类 A 中的方法 f(double x, double y),方法的重写是根据方法的名称、参数类型以及参数数量来匹配的。当调用 b.f(3, 5) 时,会调用类 B 中的方法 f(int x, int y),因为参数是整数类型,所以返回值为 3 * 5 = 15.0。而调用 b.f(3.0, 5.0) 时,会调用超类 A 中的方法 f(double x, double y),因为参数是浮点数类型,所以返回值为 3.0 + 5.0 = 8.0。
相关问题
请说出E类中【代码1】和【代码2】的输出结果。 class A { double f(double x,double y) { return x+y; } } class B extends A { double f(int x,int y) { return x*y; } } public class Main { public static void main(String args[]) { B b=new B(); System.out.println(b.f(3,5)); //【代码1】 System.out.println(b.f(3.0,5.0)); //【代码2】 } }
代码1的输出结果为15.0,代码2的输出结果为8.0。
在代码1中,方法f被调用时传入的参数类型为int,因此调用的是B类中的f方法,返回3和5的乘积,即15.0。
在代码2中,方法f被调用时传入的参数类型为double,因此调用的是A类中的f方法,返回3.0和5.0的和,即8.0。因为B类中的f方法的参数类型和A类中的f方法不同,因此B类中的f方法并没有覆盖A类中的f方法。
public class a{returnType menthodA(byte x,double y) return (short) x/y*2;} 给定如下Java代码,方法methodA返回类型是什么
给定Java代码中,方法methodA的返回类型为short。因为在方法体中,先将byte类型的x强制转换为short类型,然后除以y(double类型),最后结果乘以2,由于short类型和double类型进行运算时,short类型会自动转换为int类型,所以最终的结果是int类型,但是由于方法定义中返回类型为short,因此需要将int类型的结果强制转换为short类型再返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)