Nimrod
Nimrod

Reputation: 1140

Duplicate initialization both in subclass & supreclass

Lately, I came across this example:

Abstract Car class

    public abstract class Car {

    private final Product product;
    private final String carType;

    public Car(Product product,String carType){
        this.product = product;
        this.carType = carType;
    }
}

BigWheel Class which extends Car class

    public class BigWheel extends Car {

    private final Product product;
    private final String carType;

    public BigWheel(Product product, String carType) {
        super (product, carType);
        this.product = product;
        this.carType = carType;
    }
}

My question is simple - why would one want to initialize product & carType variables twich in both classes? why initializing them in the super isn't enough?

Upvotes: 2

Views: 109

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109547

It would have been sufficient to make the fields protected in the base class if the child class wants to immediately access the parent's fields.

It could also be a missing clean-up after copying the class source. So check the field's usage, and maybe other child classes.

public abstract class Car {

    protected final Product product;
    protected final String carType;

    public Car(Product product,String carType){
        this.product = product;
        this.carType = carType;
    }
}

Upvotes: 1

vv88
vv88

Reputation: 173

Your SuperClass and subclass have same private variables name. So when you call super from subclass, the members belonging to superclass are initialised which are not visible to subclass. Hence, subclass members need to be initialized again. But, i do not understand why would somebody have superclass & subclass with the same final members and how would they fit in bigger picture.

Upvotes: 2

Rufi
Rufi

Reputation: 2645

It is redundant to initialize the properties with the same name in the child class. As you noticed it is enough to do it in super class.

Upvotes: 0

Related Questions