Aberduc
Aberduc

Reputation: 1

creating a constructor using a instance of a superclass in java

I have this class (let's call it A) and an inherited class (B), and I would like to create a constructor for B using an instance of A, something like :

public B(A a){
   super = a;
   ...
}

Obviously the above code does not work, but is there a way to do it? I could create another instance of A with the same values for each field, but that seems really useless since I already have one, and I just need to add a few fields to make it of class B.

Upvotes: 0

Views: 54

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

I would implement this using some sort of copy constructor:

public class B extends A 
{
    private int field;

    public B(A a, int fieldValue) 
    {
        this.aFieldFromA = a.aFieldFromA;
        this.anotherFieldFromA = a.anotherFieldFromA;
        this.field = fieldValue;
    }
}

Upvotes: 0

iullianr
iullianr

Reputation: 1284

You cannot "add" a few fields to an instance of a class to make it of another class. The fields are added to a class, not to an instance of it. So I guess you will have the following options:

  • since B is derived from A your constructor of B will have to receive the information you already send to A(plus some extra fields). Which means you copy the values from your instance of A to the new instance of B
  • if you do not want to copy the values from the instance of A and continue to use that instance, then the best thing to do is to define B not derived from A, and have a field in B of type A plus the extra fields you want.

      public B {
        private A a;
        private int somefield;
        public B( A a, int somefield) {
            this.a = a;
            this.somefield = somefield;
      }
    

Upvotes: 2

Related Questions