请说出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】 } }
时间: 2023-06-15 09:04:42 浏览: 96
代码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方法。
相关问题
请分别写出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 } }
代码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。
public class shape { double x; double y; shape(double x,double y){ this.x=x;
公共类shape {
double x;
double y;
shape(double x, double y){
this.x = x;
this.y = y;
}
}
这段代码定义了一个公共的shape类,其中包括了x和y两个成员变量和一个构造函数。构造函数接受两个参数x和y,并将它们赋值给类的成员变量。这样就可以创建一个shape对象,并初始化它的位置坐标。通过这个类,我们可以创建各种不同形状的对象,并对它们进行操作和计算。这个类的定义为后续的形状操作提供了基础。