I want to copy superclass object getters to subclass object setters. But how can I do this easily. I'm looking for something like clone. Could you please me help me to find it?
A simple code:
Super class:
public class SuperClass1 {
private String name;
private String surname;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname() {
return this.surname;
}
}
Subclass:
public class SubClass1 extends SuperClass1 {
private float gpa;
public void setGpa(float gpa) {
this.gpa = gpa;
}
public float getGpa() {
return gpa;
}
}
And caller class:
public class CallerClass1 {
public static void main(String[] args) {
SuperClass1 super1 = new SuperClass1();
SubClass1 subclass1 = new SubClass1();
// How to subclass1 object values easily taken from super1
}
}
Assigning subclass object to a superclass variable Therefore, if you assign an object of the subclass to the reference variable of the superclass then the subclass object is converted into the type of superclass and this process is termed as widening (in terms of references).
Yes, the super class reference variable can hold the sub class object actually, it is widening in case of objects (Conversion of lower datatype to a higher datatype).
A superclass object is a subclass object. c. The class following the extends keyword in a class declaration is the direct superclass of the class being declared.
You can always successfully cast a superclass to a subclass. An interface can be a separate unit and can be compiled into a bytecode file. The order in which modifiers appear before a class or a method is important. Every class has a toString() method and an equals() method.
If performance is not an issue here, you can copy all the properties from one class to the other making use of reflection.
Check this link to this other question that explains how to do it:
Copy all values from fields in one class to another through reflection
This other link will give you the code, without using BeanUtils:
http://blog.lexique-du-net.com/index.php?post/2010/04/08/Simple-properties-Mapper-by-reflection
I always make use of this kind of functions in my projects. Really usefull.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With