Aug 19, 2014

20. Protected

Protected members can be seen by the same package, as well as its subclass.




The superclass, Ex20, has 3 instance variables. The String instance variable is protected.


// Ex20.java
package com.javaAndroid.ex20;

public class Ex20 {
 int a = 5, b = 8;
 protected String s = "Hello, Java World!";
}



The class Ex20a is derived from the class Ex20. It is in a different package, so it does not have access to the two integer instances of Ex20, which have default package access. However, it can find the String instance. It should be noted that we imported the superclass, so we can refer to it as Ex20, rather than its full name.


// Ex20a.java
package com.javaAndroid.ex20a;
import com.javaAndroid.ex20.Ex20;

public class Ex20a extends Ex20 {
 public static void main (String[] args) {
  Ex20a obj1 = new Ex20a();
  System.out.printf("s = %s",obj1.s);
 }
}



We create an object of class Ex20a, with the name obj1. If we write obj1 and then a period, we will get the suggestions, which includes the Sting s. Note, we also have some methods from the Object class, which is implicitly extended.






No comments:

Post a Comment