Java新手在这里,我试图找到以下代码块的输出:我知道我缺少一些java的基础知识,但如果有人可以指导我,我会很感激。
public class Test4 {
public static void main(String[] args) {
C c = new C(1, 2); // creates an obj c with arguments
D d = (D) c; // creates class obj 'D' and casts 'c' to D?
System.out.println(d.getP());
System.out.println(d.getProd());
}
}
public class C {
protected int m;
protected int n;
protected static int kappa = 0;
public C(int m1) {
this.m = m1;
this.n = m1;
kappa = kappa + 2;
}
public C(int m1, int n1) {
this.m = m1;
this.n = n1;
kappa = kappa + 2;
}
public int getSum() {
return m + n;
}
public int getProd() {
return m * n;
}
public static int getKappa() {
return kappa;
}
}
public class D extends C {
private int p;
public D(int p1) {
super(p1);
this.p = p1;
}
public D(int k1, int n1, int p1) {
super(k1, n1);
p = p1;
}
public int getP() {
return p;
}
public int getSum() {
return m + n + p;
}
}
答案 0 :(得分:1)
你的D类扩展了C,所以你可以使用D作为C的类型(C c = new D();
)但不能使用C作为D的类型(这是错误的D d = new C();
。
所以在你的代码中
C c = new C(1, 2); // creates an obj c with arguments
D d = (D) c; // <--this will generate ClassCastException