Tag: 向下转换

Java – 向上转发和向下转发

我知道stackoverflow中有很多文章/问题描述了Java中的向上转换和向下转换。 我知道什么是向上倾斜和向下倾斜。 但我的问题并不是特别的。 上传 – 从孩子到父母的转换 – 编译器会照顾。 不需要演员表 向下转换 – 从父级转换为子级 – 需要显式转换 public class Animal { public void getAnimalName(){ System.out.println(“Parent Animal”); } } public class Dog extends Animal{ public void getDogName(){ System.out.println(“Dog”); } } public static void main(String[] args) { Dog d = new Dog(); Animal a = d; // Upcasting a.getAnimalName(); Animal […]

我怎样才能贬低到class级’E型或至少在没有警告的情况下安全地进行?

我有超级抽象类Node和50种子类SubNode。 我有一个通用的Class ,它有一个私有var List 和一个方法,不幸的是它必须接受超类Node ALWAYS,不能将它移动到E: public void addSubElement (Node node){ if (node instanceOf E) subElements.add((E)node); else //Doing extra steps for occasional non-E nodes like discarding them silently without CastException; } 任何解决方案(Reflection?)能够在没有警告的情况下编译,抛出CastException而不是因为类型擦除而添加任何对象?? … 我不想为任何类型的子类编写相同的函数: public void addSubElement (Node node){ if (node instanceOf SubNode1) subElements.add((SubNode1)node); if (node instanceOf SubNode2) subElements.add((SubNode2)node); //if (node instanceOf SubNode50…. } 有一个像这样的方法会很好。 […]

编译时和运行时的Downcasting / Upcasting错误?

请检查以下程序。 我怀疑编译器何时会在编译器级别发出转换exception以及什么时候它将在runtime ? 喜欢下面的程序,表达 我假设(Redwood) new Tree()应该在编译时失败,因为Tree不是Redwood。 但它在compile time没有失败,正如预期的那样,它在runtime失败了! public class Redwood extends Tree { public static void main(String[] args) { new Redwood().go(); } void go() { go2(new Tree(), new Redwood()); go2((Redwood) new Tree(), new Redwood()); } void go2(Tree t1, Redwood r1) { Redwood r2 = (Redwood)t1; Tree t2 = (Tree)r1; } } class Tree […]