Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java initialize base class fields in subclass constructor

This is a very basic question about subclasses in java, I still don't get it...

Suppose I have a superclass with three fields and with only the default constructor:

public class Superclass {
    public int a;
    public int b;
    public int c;
}

and I want to add a field x. I cannot change Superclass, so I make a subclass:

public class Subclass extends Superclass {
    public int x;
    public Subclass(Superclass s) {
        super();
        // what to do??
    }
}

I now want to generate a Subclass object from an existing Superclass object:

Superclass s = new Superclass();
s.a = "a";
s.b = "b";
Subclass sc = new Subclass(s);
sc.x = "x";

such that I can still access sc.a, sc.b etc.

How can I best do this without assigning all these fields 'by hand' in the constructor of the subclass?

like image 306
user1981275 Avatar asked Oct 19 '25 02:10

user1981275


1 Answers

You have to assign a value to the variables either in the base-class constructor or in the child class.

You can declare a parameterized constructor in sub-class to assign the value to a variable in the superclass

class Subclass extends Superclass {
public int x;
public Subclass(int a,int b, int c,int x) {
    super();
    this.x = x;
    this.a=a;
    this.b=b;
    this.c=c;
 }
}

Or you can declare a parameterized constructor in BaseClass, and in child class, instead of calling super(), call that parametrized constructorsuper(a,b,c)

class Superclass {
public int a;
public int b;
public int c;

public Superclass(int a, int b, int c) {
    this.a = a;
    this.b = b;
    this.c = c;
 }   
}

class Subclass extends Superclass {
public int x;

public Subclass(int a,int b, int c,int x) {
    super(a,b,c);
    this.x = x;
 }
}
like image 196
Ashishkumar Singh Avatar answered Oct 21 '25 14:10

Ashishkumar Singh