13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.4 Encapsulati<strong>on</strong>, Inheritance, and Polymorphism87Example 3.26 A class that implements an interfaceclassSampleimplements Identifiable{private int id;}public void method(){System.out.println(id);}public int getID(){return id;}and assign an instance of the Sample class to it. In fact, you could assign aninstance of any class that implements the Identifiable interface to it.Interfaces may also have an extends keyword. In other words, an interfacemay inherit from an existing interface. This may be useful if you know you willwant to use methods from both the extended and the base interface withouthaving to cast the object reference. Otherwise extending an interface isunnecessary since a given class may implement as many interfaces as desired.3.4.2.1 Inheritance and Encapsulati<strong>on</strong>Encapsulati<strong>on</strong> and inheritance are related to <strong>on</strong>e another and are c<strong>on</strong>trolled byaccess modifiers <strong>on</strong> classes, data members, and methods. Let’s spend a little timetalking about these modifiers and what they mean.The access modifier keywords are public, private, and protected.When a data member or method is private, it can <strong>on</strong>ly be accessed or calledfrom within this specific class. Neither classes that extend this class, nor classesoutside this class may access such a data member or call such a method. However,<strong>on</strong>e instance of a class can access private members of another instanceof the same class. We d<strong>on</strong>’t encourage such use.When a data member or method is marked protected, however, the <strong>on</strong>lyclasses that can access such a data member or method are either 1) classes thatextend this class and their descendants, or 2) other classes in this package (even

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!