简体   繁体   English

Java:声明为父类,但实例化为Child,然后在Child中使用唯一方法

[英]Java: Declare as a parent class, but instantiate as Child, then using the unique method in Child

I ran into this problem because I need to instantiate based on user input. 我遇到了这个问题,因为我需要根据用户输入实例化。 Considering the following. 考虑以下。

   public class Parent{
       public void foo(){
         System.out.println("foo");
       }
   }

   public class Child extends Parent{
       public void UniqChildMethod(){
          System.out.println("I am unique")
       }
   }

I need to create parent or child based on user input.So lets say if the input is 0. mother object is created, if the input is 1, child is created. 我需要根据用户输入创建父级或子级。因此,假设输入为0。创建母对象,如果输入为1,则创建子级。 Since a bunch of share methods will be call on this object, i dont want to write the same code twice under if/else condition. 由于将在此对象上调用一堆share方法,因此我不想在if / else条件下两次编写相同的代码。 So my workaround is that, I create a parent object set to null, and instantiate base on user input. 因此,我的解决方法是,创建一个设置为null的父对象,并根据用户输入实例化该对象。

Here is when problem came: 这是问题出现的时间:

public static void main(String argv[]) {
        Parent obj = new Child();

        obj.UniqueChildMethod();   <--- The method is underfined for the type parent
   }

is there a workaround for this issue? 有没有解决此问题的方法?

If you know your Parent is indeed a Child object reference, yo can cast it and call child methods: 如果您知道您的Parent确实是Child对象的引用,则可以将其强制转换并调用child方法:

((Child) obj).UniqueChildMethod();

In typical app, one should check for object type before class to avoid ClassCastException : 在典型的应用程序中,应在类之前检查对象类型,以避免ClassCastException

if (obj instanceof Child) {
   Child childObj = (Child) obj;
   childObj.UniqueChildMethod(); 
}

You can use switch to solve this problem. 您可以使用switch解决此问题。

 public static void main(String argv[]) {
    Parent obj = null;
    Scanner scanner = new Scanner(System.in);
    int x = scanner.nextInt();

    switch (x){
        case 0 :    obj = new Parent();
                    obj.foo();
                    break;
        case 1 :    obj = new Child();
                    ((Child) obj).UniqChildMethod();
                    break;
                    default: obj = null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM