Tony Tarng
Tony Tarng

Reputation: 749

Java: Private variables used in inherited methods

I'm fairly new to Java, and according to my knowledge, variable drawingChar in class Shape is private, so it isn't inherited by class Test, but since setDrawingChar() is a public function, it is inherited.

public class Shape {

    private char drawingChar = '*'; // private var

    public void setDrawingChar(char drawingChar) {
        this.drawingChar = drawingChar;
    }
} 
public class Test extends Shape{

    public static void main(String[] args) {
        Test t2 = new Test();
    t2.setDrawingChar('*'); // call setDrawingChar on a Test obj
    }
}

In class Test, somehow I'm allowed to call setDrawingChar() on a Test object, but isn't it true that Test doesn't inherit drawingChar? If so, what is this.drawingChar referring to in object t2's case?

Upvotes: 1

Views: 78

Answers (1)

Jeeter
Jeeter

Reputation: 6105

Subclasses will inherit any public or protected variables or methods, and can choose to leave them alone or override them (in the case of methods). That's why you can call the method setDrawingChar, it checks Test for any method by that name, and then checks its superclasses for an implementation. It finds the implementation from Shape and executes that.

Note that you would not be able to use the Shape variable drawingChar, since the private scope is only limited to other Shape objects and not their subclasses

More info on public, private, and protected at the javadocs website for access control.

Upvotes: 3

Related Questions