Raounak Sharma
Raounak Sharma

Reputation: 375

Need explanation on: Private Access modifier in java

I have two classes in Java: Fist class is extending Person class. I have a variable eyecolor in Person which is private and I have a public setter and getter for it.

Now if I extend it in Fist class then I can set the variable and I can also get it.

My question is if eyecolor is a private member of a class Person, why am I not getting an error of using a private member? Why is this code working? Is the eyecolor data member getting inherited?

Person Class

package lets_start;

public class Person {
    private String eyecolor;

    public String getEyecolor() {
        return eyecolor;
    }

    public void setEyecolor(String eyecolor) {
        this.eyecolor = eyecolor;
    }
}

Fist class

package lets_start;

public class Fist extends Person {
    public static void main(String[] args) {
        Fist f = new Fist();
        f.setEyecolor("Brown");
        System.out.println(f.getEyecolor());
    }
}

Output:

Brown

Upvotes: 0

Views: 69

Answers (2)

mplwork
mplwork

Reputation: 1140

You aren't accessing the private member, you are accessing a public method.

Accessing the private member looks like this and will create a compile time error:

package lets_start;

public class Fist extends Person {
    public static void main(String[] args) {
        Fist f = new Fist();
        f.eyecolor = "Brown";
        System.out.println(f.eyecolor);
    }
}

Upvotes: 0

Jonathan
Jonathan

Reputation: 792

To access/edit it from child classes, either make the field protected/package-private or use the getter/setter you defined in Person.

See https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html


why I be able to access it from its child classam not getting an error of using a private member? Why is this code working? Is the eyecolor data member get's inherited?

Because you access it through the public getter/setter which are inherited from Person. To make it clearer, eyecolor field is not inherited, getter/setter are.

Please feel free to edit your question or comment if it is unclear.

Upvotes: 1

Related Questions