java 运行多态

来源:百度知道 编辑:UC知道 时间:2024/05/28 23:16:30
import java.io.*;
import java.util.*;
class A{
private int a;
A(int x){ this.a=x; }
void show(){ System.out.println("A类的show()"); }
}
class B extends A{
B(int x){ super(x); }
void show(){ System.out.println("重写父类A的show()为B的show()"); }
void color(){ System.out.println("显示黑色,B类新增方法"); }
//void pr(){ System.out.println(this.x); }
}
class C extends B{
private int m;
private int n;

C(int e) { this.m=e; }
//编译通不过,怎么会事

void show(){ System.out.println("再次重写父类B(A的子类)的show()为C的show()"); }
}
class example{
public static void main(String[] qp){
A a=new B(12);
a.show();
//a.pr();
}
}

解决方法有两种:

第一种: 类 C 继承类B ,因为B类没有提供无参构造方法,A类也没提供无参构造方法,所以你现在, 类 C 继承类B ,你要为 类B传参.
在类C的构造函数里加上一个
C(int e) {
super(e);
this.m = e;
}
这是一种解决方法

第二种: 在 C类的父类里都写一个 无参的构造方法(默认构造方法),OK!

父类没有默认构造方法,A,B类中都要有

class example 前加public
C(int e) { this.m=e; }前加void
还有就是前位来兄说的