Search code examples
javaandroidinheritanceprivatechronometer

Inheritance and private variables in Java


I'm trying to add a method to the Chronometer class in android. It stores the start time in this variable:

private long mBase;

so I thought I could do this

public class MyChronometer extends Chronometer{

    public void reset(){
        long now = SystemClock.elapsedRealtime();
        this.mBase = now;
    }
}

but Android Studio is telling me that mBase can't be found. Why is this? And what am I doing wrong? From what I understand of inheritance in Java, if I extend a class then I have all of the methods and variables of the class I extend which I can then add to. Is this incorrect? Wouldn't this include the mBase variable even though it is private?

Edit: Essentially I am trying to create a setter function for mBase


Solution

  • I'm quoting the tutorial - Private Members in a Superclass:

    A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

    Meaning that you cannot directly access the private fields, but you can use methods that give you access to them. This table might be helpful as well:

                      Access Levels
    ------------+---------+---------+-----------+------
    Modifier    |   Class | Package |  Subclass | World
    ------------+---------+---------+-----------+------
    public      |     Y   |    Y    |     Y     |   Y
    protected   |     Y   |    Y    |     Y     |   N
    no modifier |     Y   |    Y    |     N     |   N
    private     |     Y   |    N    |     N     |   N