在java中将父类转换为子类
考虑一下这个场景 我有两个班,分别是学生班和优等生班在java中将父类转换为子类,java,inheritance,Java,Inheritance,考虑一下这个场景 我有两个班,分别是学生班和优等生班 class Student{ String name; int roll; Student(String name, int roll){ this.name = name; this.roll = roll; } } class HonorStudent extends Student{ int honorid; HonorStudent(Stri
class Student{
String name;
int roll;
Student(String name, int roll){
this.name = name;
this.roll = roll;
}
}
class HonorStudent extends Student{
int honorid;
HonorStudent(String name, int roll,int honorid){
this.name = name;
this.roll = roll;
this.honorid = honorid;
}
HonorStudent(String name, int roll){
this.name = name;
this.roll = roll;
}
}
现在,可能有一些场景,我想把一个学生变成一个优秀的学生。由于在这种情况下不允许向下投射,我不能这样做:
Student s1 = new Student("abc",123);
HonorStudent s = (HonorStudent)s1;
另一种方法是在HonorStudent中定义一个方法,输入一个Student对象并返回一个HonorStudent:
public static HonorStudent convertToHonor(Student s){
return new HonorStudent(s.name,s.roll);
}
如果只有两个属性(姓名、掷骰),这很方便,但是如果我有很多属性,比如说50,该怎么办?在这种情况下,我必须将每个属性都输入到HonorStudent
我强烈认为可能有一种更简单的方法来做这件事?你在问是否有一种更方便的方法来做这件事。如果我们只考虑将参数从一个对象复制到另一个对象,那么就没有其他的方法来实现这一点。解决这个问题的方法可能是将对象用于成员字段组,或者通过可以将同名成员字段从对象复制到另一个对象的代码将其自动化 小补丁 但首先,让我们稍微改进一下设计。类层次结构中的类之间不应像这样重复字段。因此,让我们消除这种重复:
public class Student {
private String name;
private int roll;
public Student(String name, int roll) {
this.name = name;
this.roll = roll;
}
public String getName() {
return name;
}
public int getRoll() {
return roll;
}
}
public class HonorStudent extends Student {
private int honorId;
public HonorStudent(String name, int roll, int honorId) {
super(name, roll);
this.honorId = honorId;
}
public int getHonorId() {
return honorId;
}
}
复制构造函数
如果真的需要复制对象,那么复制构造函数可能很有用。创建副本构造函数将允许您跳过只传递一个成员字段
public Student(Student other) {
this.name = other.name;
this.roll = other.roll;
}
然后,创建荣誉学生的学生部分变得更简单
public HonorStudent(Student student, int honorId) {
super(student);
this.honorId = honorId;
}
设计
现在,对象更改其类型并不常见。所以这不是一件普通的事情。这通常通过不同类型的类设计来解决。例如,honorId
可能是Student
类的一部分,因为我想,学生可以获得或失去这个属性。与荣誉相关的行为可以发生在学生课堂上的其他课堂上
阅读相关的书籍可能会很有用。选择哪种模式取决于用例和您试图解决的问题。您的问题不清楚谢谢,这很有帮助。对不起,我没有注意到复制品fields@GopalaKrishnan伟大的如果这解决了您的问题,请随意接受答案:)