How to make variable in companion object protected

Viewed 193

I want to make a variable in companion object protected. I think when I make the variable protected, it would be accessible only from another class which inherit the variable's class, not from other classes or functions. But It doesn't work.

Here's my code

open class Population{
    companion object{
        @JvmStatic // Though I added it because of recommendation of IntelliJ, It still doesn't work.
        protected var population_quantity: Int = 0
    }
}

class Marin : Population(){
    init{
        population_quantity += 1 // I want to make it possible
    }
}

class Checker : Population() {
    fun printPopulationQuantity()
    {
        println(population_quantity) // I also want to make it possible
    }
}

fun main(){
    var m1 = Marin()
    var checker = Checker()

    // But I want to make codes below here impossible
    // Population.population_quantity += 1
    // println(Population.population_quantity)
}

Below is what I want to make which is made via C++. I hope below would clarify what I'm saying.

#include <iostream>

class Population
{
    protected:
        static int population_quantity;
};
int Population::population_quantity = 0;

class Marin : Population
{
    public:
        Marin()
        {
            std::cout << "Marin is generated" << std::endl;
            population_quantity += 1;
        }
        ~Marin()
        {
            std::cout << "Marin is dead" << std::endl;
            population_quantity -= 1;
        }
};

class Checker : Population
{
    public:
        void printPopulationQuantity()
        {
            std::cout << population_quantity << std::endl;
        }
};

int main()
{
    Checker checker;
    checker.printPopulationQuantity();
    Marin *m1 = new Marin();
    checker.printPopulationQuantity();
    
    // std::cout << "population : " << Population::population_quantity << std::endl;
    // Can't access population_quantity from main which doesn't inherite Population
    // because Population::population_qantity is protected.
    // But it is possible to access Population:population_quantity from Marin which inherits Population.

    delete m1;
    checker.printPopulationQuantity();
    return 0;
}

When you help me solve this problem, I'm sure that I would feel sincere thankful from bottom of my heart.

1 Answers

That is probably because in class Checker : Population you have a void function which is in public. Try changing it to this:

class Checker : Population
{
    protected:
        void printPopulationQuantity()
        {
            std::cout << population_quantity << std::endl;
        }
};
Related