Introduction to Protected Access Specifier
First, you should be aware that you don’t need to understand this section to continue through inheritance. The protected keyword deals with a concept called inheritance, which takes an existing class and adds new members to that class without touching the existing class, which we refer to as the base class.
The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
Syntax
class Parent {
//protected data members
}
class Child extends Parent {
//use protected data members of Parent class
}
Example
1. /**
2. * @(#)ProtectedDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/16
7. */
8.
9. // A simple class hierarchy.
10. // A class for two-dimensional objects.
11. class TwoDShape {
12.
13. protected double width;
14. protected double height;
15.
16. void showDim() {
17. System.out.println("Width and height are " +
18. width + " and " + height);
19. }
20.
21. }
22.
23. // A subclass of TwoDShape for triangles.
24. class Triangle extends TwoDShape {
25.
26. String style;
27.
28. double area() {
29. return width * height / 2;
30. }
31.
32. void showStyle() {
33. System.out.println("Triangle is " + style);
34. }
35. }
36.
37. class Shapes {
38.
39. public static void main(String args[]) {
40.
41. Triangle t1 = new Triangle();
42.
43. t1.width = 8.0;
44. t1.height = 12.0;
45. t1.style = "right";
46.
47. System.out.println("Info for t1: ");
48.
49. t1.showStyle();
50. t1.showDim();
51.
52. System.out.println("Area is " + t1.area());
53.
54.
55. }
56. }
Output
Info for t1:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0
