首页 > 解决方案 > 如何区分被转换为不同子类对象的父类?

问题描述

我是 Java 新手,仍在学习 OOP 概念。我陷入了一个问题。我有 2 个 java 文件来运行程序,我面临的问题是如何从父类对象调用子类方法?

测试包

package test;

public class Parent{
    private String name;

    public void setName(String a){this.name = a;}
    public String getName(String a){return this.name;}

    Parent(String a){
        this.name = a;
    }
}

儿童A类:

package test;

public class ChildA extends Parent{
    private int scoreA;

    public void setScoreA(int a){this.scoreA = a;}
    public int getScoreA(int a){return this.scoreA;}

    ChildA(String a, int b){
        super(a);
        this.scoreA = b;
    }
}

儿童B班

package test;

public class ChildB extends Parent {
    private int scoreB;
    
    public void setScoreB(int a){this.scoreB = a;}
    public int getScoreB(int a){return this.scoreB;}

    ChildB(String a, int b){
        super(a);
        this.scoreB = b;
    }
}

测试 2 包

import test;

public class Validate{
    public Parent checkDetail(String a, String b, int c){
        if(b.equals("A")){
            Parent p = new ChildA(a,b,c);
            return p;
        }
        else if(b.equals("B")){
            Parent p = new ChildB(a,b,c);
            return p;
        }
        else
            return null;
    }
}

主包

import test;
import test2.Validate;
import java.util.*;

public class User{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.println("Name: ");
        String name = sc.nextLine();
        System.out.println("Type: ");
        String type = sc.nextLine();
        System.out.println("Score: ");
        int score = sc.nextInt();
        Validate v = new Validate();
        Parent p = v.checkDetail(name,type,score);
        if(p==null)
            System.out.println("Invalid");
        //WHAT I WANT TO DO
        /* If Parent object p returns child of type A, then run method score A
        else if of type B, then run method score B*/
    }
}

几件事要补充:

标签: javaoop

解决方案


也许只是这样:

if (p instanceof ChildA) {
    ((ChildA)p).setScoreA(something);
} else if (p instanceof ChildB) {
    ((ChildB)p).setScoreB(something);
}

推荐阅读