/** * This code is from the book: * Winder, R and Roberts, G (1998) * Developing Java Software * John Wiley & Sons. * It is copyright (c) 1997 Russel Winder * and Graham Roberts. */ class Superclass{ public int i = 5; protected int j = 10; private int k = 20; //Method that will be inherited but //not accessible in a subclass private void f(){ System.out.println("f"); //Can call g and h //g(); //h(); } //Method that will be inherited and is accessible to //a subclass and other classes in the same package protected void g(){ System.out.println("f"); //Can call f and h //f(); //h(); } //Shared method that is not overridden //in the subclass public void h(){ System.out.println("Shared"); //Can call f and g() //f(); //g(); } } class Subclass extends Superclass{ public void test(){ i = 10; //OK inherited public variable j = 20; //OK inherited protected variable //k = 30; //Error - cannot access inherited //private variable //f(); //Error as f is private in superclass g(); h(); } } public class l1Inherit3{//Inherit2 public static void main(String[] args){ Superclass superclass = new Superclass(); //superclass.f(); //Error method f is private //Can call g because //although the method is protected, //this class is in the same package superclass.g(); superclass.h(); Subclass subclass = new Subclass(); subclass.test(); //Error method f is inherited but private //subclass.f(); //Can call g because //although the method is protected, //this class is in the same package subclass.g(); subclass.h(); } } /******** sample compilation & run ******** # javac l1Inherit3.java # java l1Inherit3 f Shared f Shared f Shared # ******************************************/