我想调用一个超类Object的子类方法但是因为我在子类中声明了另一个整数,它给了我一个异常,是否有解决方法来实现这一点?
public static void main(String[]args){
A a = new A(2,3);
B b = new B(3,5,6);
System.out.println("A object: ");
a.showij();
System.out.print("sum = ");
((B) a).sum(); < ==== this line gives me the error, can't cast
System.out.println("B object: ");
b.showij();
System.out.print("sum = ");
b.sum();
}
public class B extends A {
int k;
public B(){
super();
}
public B(int a, int b, int c) {
super(a, b);
k = c;
}
public void sum(){
System.out.println( i + j + k);
}
}
public class A {
int i,j;
public A() {
}
public A( int a, int b){
i = a;
j = b;
}
public void showij(){
System.out.println("\ti: " + i + " j: " + j);
}
}
*编辑:这是完整的事情
答案 0 :(得分:1)
如果B扩展A,这仍然意味着A是一个单独的类,当你仅实例化A时,你不能将它强制转换为B,因为它与B无关。
您可以将B转换为A,因为派生类总是可以转换为它的超类。事实上,你甚至不需要演员。但这是不可能的,反之亦然。
假设B延伸A。
B b = new B(1,2,3,4,5);
A a = b; <- This is valid.
a.sum();
这将通过语法正确,但它仍会调用B的和函数,因为它是B的对象。
但是,在Java中,您无法在类外部显式调用超级函数,就像在C ++中一样。您必须在函数中对此进行deicde,然后从B中调用它:
class B extends A
{
@Override
public int sum()
{
super.sum();
}
}
如果不希望这样,你必须声明一个不被派生类覆盖的不同函数名,但你不能依赖于特定的行为,除非你让类成为final,以确保它不能得出。
<强>更新强>
示例代码:
public class A
{
private int mI;
private int mJ;
public A(int i, int j)
{
mI = i;
mJ = j;
}
public int sum()
{
return mI+mJ;
}
public void showij()
{
System.out.println("I: "+ mI + " J: "+mJ);
}
public void print()
{
System.out.println("A called "+ sum());
}
}
B级:
public class B
extends A
{
private int mK;
public B(int i, int j, int k)
{
super(i, j);
mK = k;
}
public int sum()
{
return super.sum()+mK;
}
public void showk()
{
System.out.println("K: "+ mK);
}
public void print()
{
System.out.println("B called "+ sum());
}
}
测试主要:
public class test
{
public static void main(String[] args)
{
A a = new A(1, 2);
B b = new B(3, 4, 5);
a.print();
b.print();
a.showij();
b.showij();
b.showk();
a = b;
b.print();
}
}
答案 1 :(得分:0)
您的代码已编译,因为它有效将类型强制转换为其子类。但是,由于这个原因导致了类强制转换的运行时异常。
A a = new A(2,3); --> Your instance is of type A
((B) a).sum(); --> and you are casting it to B, which cannot happen because the object is not of type B
然而,这个陈述会起作用
A a = new B(2,3, 6); --> As per the declaration type of instance is A but the actual instance created is B. So even if a is cast to B it works.
((B) a).sum();