class Super{ public Integer getLenght() { return new Integer(4); } } public class Sub extends Super{ public static void main(String[] args) { Super sooper = new Super(); Sub sub = new Sub(); System.out.println(sooper.getLenght().toString() + "," + sub.getLenght().toString()); } public Long getLenght() { return new Long(5); } }
时间: 2024-04-03 20:31:00 浏览: 23
这段代码中,父类Super定义了一个返回Integer类型的getLength()方法,而子类Sub重写了这个方法并返回了Long类型。在main方法中,创建了一个Super类对象sooper和一个Sub类对象sub,并分别调用它们的getLength()方法并输出结果。由于Java的多态性,调用sooper.getLenght()方法时会执行父类的方法并返回Integer类型的4,而调用sub.getLenght()方法时会执行子类的方法并返回Long类型的5。因此,输出结果为"4,5"。
相关问题
如下代码class Super { publiclntegergetLenght(){ return new Integer(4); )}public class Sub extends Super (publicLonggetLenght()( return new Long(5); 3public static void main(Stringl args)(Super sooper = new Super();Sub sub = new Sub();System.out.println(sooper.getLenght().toString() + ".sub.getLenght().toString() )}}输出是什么
代码存在语法错误,需要进行修正,修正后的代码如下:
```
class Super {
public Integer getLength() {
return new Integer(4);
}
}
public class Sub extends Super {
public Long getLength() {
return new Long(5);
}
public static void main(String[] args) {
Super sooper = new Super();
Sub sub = new Sub();
System.out.println(sooper.getLength().toString() + ", " + sub.getLength().toString());
}
}
```
输出结果为:`4, 5`。因为 `sooper.getLength()` 调用的是父类 `Super` 的 `getLength()` 方法,返回值为 `4`;`sub.getLength()` 调用的是子类 `Sub` 的 `getLength()` 方法,返回值为 `5`。
class Super { public int getLength() { return 4; } } public class Child extends Super { public long getLength() { return 5; } public static void main(String[] args) { Super sub = new Child(); System.out.print(sub.getLength()); } }
在这段代码中,输出结果为5。由于Child类继承了Super类,并重写了getLength()方法,使得子类中的getLength()方法返回类型为long,而父类中的getLength()方法返回类型为int。当子类实例化后,调用getLength()方法时,会优先调用子类中的getLength()方法,输出结果为5。这是因为Java中的方法重写是基于运行时动态绑定的,即子类方法会覆盖父类方法,调用的方法取决于实例化对象的类型。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)