protected | CodeGuru

protected

Bruce Eckel’s Thinking in Java Contents | Prev | Next Now that you’ve been introduced to inheritance, the keyword protected finally has meaning. In an ideal world, private members would always be hard-and-fast private, but in real projects there are times when you want to make something hidden from the world at large and yet […]

Written By
CodeGuru Staff
CodeGuru Staff
Mar 1, 2001
1 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Now


that you’ve been introduced to inheritance, the keyword


protected

finally has meaning. In an ideal world,


private

members would always be hard-and-fast


private

,


but in real projects there are times when you want to make something hidden


from the world at large and yet allow access for members of derived classes. The


protected

keyword is a nod to pragmatism. It says “This is


private

as far as the class user is concerned, but available to anyone who inherits


from this class or anyone else in the same


package

.”


That is,

protected
in Java is automatically “friendly.”

The


best tack to take is to leave the data members

private
– you should always preserve your right to change the underlying
implementation. You can then allow controlled access to inheritors of your
class through
protected
methods:
//: Orc.java
// The protected keyword
import java.util.*;
 
class Villain {
  private int i;
  protected int read() { return i; }
  protected void set(int ii) { i = ii; }
  public Villain(int ii) { i = ii; }
  public int value(int m) { return m*i; }
}
 
public class Orc extends Villain {
  private int j;
  public Orc(int jj) { super(jj); j = jj; }
  public void change(int x) { set(x); }
} ///:~ 

You


can see that


change( )

has access to


set( )

because it’s


protected

.

Contents

|

Prev

|

Next
CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.