Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an object of a subclass access protected field of another object of another subclass?

I learnt the following from the book Core Java, Volume I--Fundamentals (8th Edition) > Chapter 5: Inheritance > 'Protected Access' section (Page 205).

There are times, however, when you want to restrict a method to subclasses only or, less commonly, to allow subclass methods to access a superclass field. In that case, you declare a class feature as protected. For example, if the superclass Employee declares the hireDay field as protected instead of private, then the Manager methods can access it directly.

However, the Manager class methods can peek inside the hireDay field of Manager objects only, not of other Employee objects. This restriction is made so that you can’t abuse the protected mechanism and form subclasses just to gain access to the protected fields.

I wrote the following code to test it.

class Employee
{
    protected String name;

    public Employee(String name) {
        this.name = name;
    }
}

class Manager extends Employee
{
    public Manager(String name) {
        super(name);
    }

    public void peekName(Employee e) {
        System.out.println("name: " + e.name);
    }
}

class Executive extends Employee
{
    public Executive(String name) {
        super(name);
    }
}

public class TestProtectedAccess
{
    public static void main(String[] args) {
        Employee e = new Employee("Alice Employee");
        Manager m = new Manager("Bob Manager");
        Executive ex = new Executive("Charles Executive");

        // Manager object accessing protected name of Employee object
        m.peekName(e);

        // Manager object accessing protected name of Executive object
        m.peekName(ex);
    }
}

The output of the code is:

$ java TestProtectedAccess
name: Alice Employee
name: Charles Executive

The Manager object m is able to access protected field name of other Employee objects e and ex. This seems to contradict what I have quoted above from the book, especially the part that I have highlighted in bold.

Can someone explain me if the book is wrong or is my understanding wrong? If my understanding is wrong can you suggest a better example to understand what the book means?

like image 471
Cute Learner Avatar asked Oct 31 '22 17:10

Cute Learner


1 Answers

Since your classes are all in the same package , protected is the same as public.

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

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

like image 76
Roman Pustylnikov Avatar answered Nov 08 '22 07:11

Roman Pustylnikov