2014-03-05 42 views
1

我有这样的代码。将超类的对象转换为子类

超级类

public class Actual { 
    public int x = 123; 
} 

子类

public class Super extends Actual{ 
    public int x = 999; 
    public int y = 12345; 
} 


public class Sub extends Super { 
    public int x = 144; 
} 

所以问题是我能转换超类对象到子类? 这是正确的这个问题我试过了吗?

public class Mid1Prob1 { 
    public static void main(String[] args) { 
     System.out.println("Testing..."); 
     int x = 3; 
     Actual actual = new Super(); 
     System.out.println(actual.x); 


     Super super1 = new Super(); 
     System.out.println(super1.x); 


     Actual act = new Actual(); 

     act = new Sub(); 
     System.out.println(act.x); 
    } 
} 

但它赋予Class Cast异常。

+1

发布异常跟踪 –

+4

您提供的代码段不会抛出ClassCastException。 – Radiodef

+0

你的代码中没有任何地方是你将一个超类转换为子类。你在哪里得到ClassCastException? – TheLostMind

回答

4

您可以将Child类转换为Super类,但反之亦然。 如果汽车是超级汽车,汽车是子类,那么所有汽车(儿童)都是汽车(超级),但并非所有汽车都是汽车。

+0

+1完美ANS花花公子:) – Krishna

+0

@Krishna欢迎:) –

+0

:)我盖尔德有ANS – Krishna

2

有没有可能做到这一点。你只能这样。 Actual s = new Super();Super sp = new Super();Actual a = new Actual();没有其他的可能性。只有那个assigment可能不会抛出classcast Exception。

+0

如何'超级S =新的实际();'是可能的? –

+0

误解。我做了改变。 – RMachnik

+0

你试过吗? –

2

我可以转换成超类对象到子类?

没有,你只能做它的其他方式。您只能将子类对象分配给超类参考。

原因是,子类可以有更多的功能和更具体的问题。如果您允许将超类对象提交给子类,那么该超类对象将如何获得这些子类功能?

+1

+1更接近ans。:) – Krishna

1

这些都是创建超类和子类的对象的唯一方法:

Actual act = new Actual(); 
Actual actual = new Super(); 
Actual actual2 = new Sub(); 

Super super1 = new Super(); 
Super super2 = new Sub(); 

Sub sub = new Sub(); 

有没有其他办法。如果你尝试过,它会给你编译时间错误,以铸造你的课程或给运行时间错误java.lang.ClassCastException

+0

如果你能创建实际的超级类对象,你将能够通过这个实际的对象访问超类的int? – Krishna

+0

任何方式+1为你的答案哥们。 – Krishna

+0

可能这个链接将有助于理解,http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15 –