Search code examples
javaabstract-class

Subclass editing declared abstract classes classmember


I have an abstract class that subclasses will inherit. I want to have a get method that returns the amount of passengers. I declare this method in the abstract class and it will return the passengers.

The class member passengers is not defined but instantiated, so the get method knows what variable to return.

In the subclasses, I want this variable to have different values.

However, the get method returns 0 even when the amount of passengers is not 0.

I have tried writing: passengers = random.nextInt(4) + 1;

Abstract class vehicle

import java.util.Random;

public abstract class Vehicle {
    protected Random random = new Random();
    protected int passengers;

    public int getPassengerAmount() {
        return this.passengers;
    }
}

Class Car

public class Car extends Vehicle {
    private String name = "Car";
    private int size = 1;
    public int passengers = random.nextInt(4) + 1;
}

Solution

  • You are masking the parent variable by redeclaring the passengers variable in the Car class.

    You should initialize the parent variable in the constructor of the child instead:

    public class Car extends Vehicle {
    
        private String name = "Car";
        private int size = 1;
    
        public Car() {
            this.passengers = random.nextInt(4) + 1;
        }
    
    }
    

    If you want it to be public, then you should make it public in the Vehicle class, but to be honest I wouldn't recommend it and I would rather go with protected variables but public getters / setters.