Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy superclass object values to subclass object values?

Tags:

java

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
  }
}
like image 836
olyanren Avatar asked Dec 12 '11 08:12

olyanren


People also ask

How we can assign the object value of subclass to superclass?

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).

Can a superclass object reference a subclass object?

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).

Can a superclass object be treated as a subclass object?

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.

Can you cast a superclass to a subclass?

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.


1 Answers

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.

like image 168
Jonathan Avatar answered Sep 29 '22 19:09

Jonathan