java - 如何区分被转换为不同子类对象的父类?
问题描述
我是 Java 新手,仍在学习 OOP 概念。我陷入了一个问题。我有 2 个 java 文件来运行程序,我面临的问题是如何从父类对象调用子类方法?
- 父类有 2 个孩子 - A 和 B
- 我不知道的是,当我返回 Parent 类的对象时,我如何确定它被投射到哪个孩子,然后运行后续方法?到目前为止我所做的工作:
测试包
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*/
}
}
几件事要补充:
- 我无法更改任何一个类的属性的变量名。所以如果一个孩子有属性A,我必须调用getA()。我不能在那里使用抽象函数。
- 里面还有很多功能。我只是复制了其中的一小部分以突出我的问题。
- 有一种方法可以为父类中的属性定义抽象方法,但在我的情况下,多个类中有多个属性,因此为每个属性编写一个抽象方法会很多。
解决方案
也许只是这样:
if (p instanceof ChildA) {
((ChildA)p).setScoreA(something);
} else if (p instanceof ChildB) {
((ChildB)p).setScoreB(something);
}
推荐阅读
- python-3.x - ubuntu16.04 python3 pip install sasl
- css - flex-wrap 属性在移动屏幕上不起作用
- javascript - 我是否正确使用了这个 Promise 功能
- javascript - 有没有办法让多个内联配置的 ckeditor 与单个工具栏 DOM 元素
- xamarin - Xamarin 表单是否支持 Google 地图本机控件的 Bing 地图?
- python - Python plt.colorbar() 它有什么作用,颜色条上的数字表示什么?
- angular - Cloud Firestore - 查询基于单个文档
- sql - SQL Server 将列名作为 where 子句参数传递
- reporting-services - SSRS 表达式嵌套 iif 表达式
- c# - 进入页面后运行一次代码