9.4 Protected Member
The private members of a class cannot be directly accessed outside the class. Only methods of that class can access the private members directly. As discussed previously, however, sometimes it may be necessary for a subclass to access a private member of a superclass. If you make a private member public, then anyone can access that member. So, if a member of a superclass needs to be (directly) accessed in a subclass and yet still prevent its direct access outside the class, you must declare that member protected.
Following table describes the difference
Modifier | Class | Subclass | World |
---|---|---|---|
public | Y | Y | Y |
protected | Y | Y | N |
private | Y | N | N |
Following program illustrates how the methods of a subclass can directly access a protected member of the superclass.
For example, let's imagine a series of classes to describe two kinds of shapes: rectangles and triangles. These two shapes have certain common properties height and a width (or base).
This could be represented in the world of classes with a class Shapes from which we would derive the two other ones : Rectangle and Triangle
Program : (Shape.java)
/**
* A class Shape that holds width and height
* of any shape
*/
public class Shape
{
protected double height; // To hold height.
protected double width; //To hold width or base
/**
* The setValue method sets the data
* in the height and width field.
*/
public void setValues(double height, double width)
{
this.height = height;
this.width = width;
}
}
Program : (Rectangle.java)
/**
* This class Rectangle calculates
* the area of rectangle
*/
public class Rectangle extends Shape
{
/**
* The method returns the area
* of rectangle.
*/
public double getArea()
{
return height * width; //accessing protected members
}
}
Program : (Triangle.java)
/**
* This class Triangle calculates
* the area of triangle
*/
public class Triangle extends Shape
{
/**
* The method returns the area
* of triangle.
*/
public double getArea()
{
return height * width / 2; //accessing protected members
}
}
Program : (TestProgram.java)
/**
* This program demonstrates the Rectangle and
* Triangle class, which inherits from the Shape class.
*/
public class TestProgram
{
public static void main(String[] args)
{
//Create object of Rectangle.
Rectangle rectangle = new Rectangle();
//Create object of Triangle.
Triangle triangle = new Triangle();
//Set values in rectangle object
rectangle.setValues(5,4);
//Set values in trianlge object
triangle.setValues(5,10);
// Display the area of rectangle.
System.out.println("Area of rectangle : " +
rectangle.getArea());
// Display the area of triangle.
System.out.println("Area of triangle : " +
triangle.getArea());
}
}
Output :
Area of rectangle : 20.0
Area of triangle : 25.0