Learn Java for Web Development

(Tina Meador) #1
APPENDIX A: Introduction to Java 389

Encapsulation


Encapsulation is the technique to achieve data hiding by preventing the data and the code from
being randomly accessed and manipulated by the external code, that is, from the code outside the
class. In terms of implementation, encapsulation is achieved by making the fields in a class private
and providing access to the fields via public methods. If a field is declared private, it cannot be
accessed by anyone outside the class. Listing A-14 illustrates an encapsulated Book class.


Listing A-14. Encapsulation


public class Book {
private String title ;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}


Inheritance


Inheritance is one of the fundamental principles in object-oriented programming. In Java, all classes
by default extend the java.lang.Object class. A class can extend another class by using the
extends keyword. Java supports single inheritance through implementation inheritance in which a
class inherits state and behaviors from another class through class extension. Java also supports
multiple inheritance in two ways.


   A class can inherit behavior from one or more interfaces by means of
implementation.
 An interface can inherit behavior from one or more interfaces through extension.

Figure A-1 presents a UML^1 class diagram that depicts a parent-child relationship between a class,
ClassA, and a child class, ClassB. ClassB is a referred to as a subclass of ClassA. Note that a line
with an arrow is used to depict generalization, in other words, the parent-child relationship.


(^1) http://www.uml.org/

Free download pdf