给出下列【代码】注释标注的代码的输出结果。 class A { int f(int x,int y) { return x+y; } } class B extends A { int f(double x,int y) { return (int)x*y; } } public class E { public static void main(String args[]) { B b=new B(); int m = b.f(3,5); int n = b.f(3.14,5); System.out.printf("%d:%d",m,n); //【代码】 } }
时间: 2024-04-04 16:07:57 浏览: 208
在上述代码中,输出结果为 `8:15`。
下面是代码的详细解释:
1. 首先,我们定义了一个 `A` 类,并在其中声明了一个名为 `f` 的方法,该方法将两个整数相加,并返回它们的和。
2. 接着,我们定义了一个名为 `B` 的子类,它继承了 `A` 类。在 `B` 类中,我们定义了一个名为 `f` 的方法,该方法接受一个双精度浮点型参数和一个整型参数,并将这两个参数相乘,然后将结果转换成整数并返回。
3. 在 `main` 方法中,我们创建了一个 `B` 的实例 `b`。然后,我们分别调用了 `b` 的 `f` 方法,并将其返回值赋值给了两个整型变量 `m` 和 `n`。具体来说,我们第一次调用 `b.f(3, 5)`,该方法将返回 `3 + 5 = 8`,我们将其赋值给 `m`;第二次调用 `b.f(3.14, 5)`,该方法将返回 `3.14 * 5 = 15.7`,我们将其转换成整数 `15` 后赋值给 `n`。
4. 最后,我们使用 `System.out.printf` 方法输出了 `m` 和 `n` 的值,结果为 `8:15`。
相关问题
给出下列【代码】注释标注的代码的输出结果。 interface Com { int computer(int m,int n); } class A implements Com{ public int computer(int a,int b){ return a+b; } } class B implements Com{ public int computer(int a,int b){ return a*b; } } class People { int a,b; int handleDigit(Com com){ return com.computer(a,b)/2; } } public class E { public static void main(String args[]){ People p = new People (); p.a =100; p.b = 2; int m = p.handleDigit(new A()); int n = p.handleDigit(new B()); System.out.printf("%d:%d",m,n);//【代码】 } }
该代码的输出结果为:
```
101:100
```
解释如下:
该代码定义了一个接口 `Com`,其中包含了一个抽象方法 `computer`,用于计算两个整数。接着定义了两个类 `A` 和 `B`,它们都实现了接口 `Com` 中的 `computer` 方法,分别用于计算两个整数的和和积。然后定义了一个类 `People`,其中包含了两个整数 `a` 和 `b`,以及一个 `handleDigit` 方法,该方法接受一个 `Com` 接口的实现类对象 `com`,调用 `com` 的 `computer` 方法计算 `a` 和 `b` 的结果,然后将结果除以 2 并返回。最后在 `main` 方法中,首先创建了一个 `People` 类的对象 `p`,并将 `a` 设置为 100,`b` 设置为 2。然后分别调用 `p` 对象的 `handleDigit` 方法,传入一个 `A` 类的实例和一个 `B` 类的实例,得到了两个结果。最终使用 `System.out.printf` 方法将这两个结果格式化输出,分别用冒号隔开,得到了输出结果 `101:100`。
给出下列【代码】注释标注的代码的输出结果。 class Animal { int m = 100; public int setM(){ return m; } } class Dog extends Animal{ int m = 6; public int setM(){ return m; } } public class E { public static void main(String args[]){ Animal dog = new Dog(); System.out.printf("%d:%d",dog.setM(),dog.m); //【代码】 } }
输出结果为:6:100。
解析:Animal类有一个变量m和一个返回变量m的方法setM(),Dog类继承了Animal类,并且重写了setM()方法。在main方法中,创建了一个Animal类型的变量dog,并且将其赋值为一个Dog类型的实例。由于Dog类重写了setM()方法,所以当调用dog.setM()时,实际上调用的是Dog类中的setM()方法,返回的是Dog类中的变量m的值,即6。而当调用dog.m时,实际上访问的是Animal类中的变量m,即100。所以最终输出结果为6:100。
阅读全文
相关推荐

















