Java Reference
In-Depth Information
Listing 1-6. The Definition of the Person2 Class in Which Data Elements Are Not Hidden by Declaring Them Public
package com.jdojo.concepts;
public class Person2 {
public String name; // Not hidden from its users
public String gender; // Not hidden from its users
public Person2(String initialName, String initialGender) {
name = initialName;
gender = initialGender;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String getGender() {
return gender;
}
}
The code in Listing 1-1 and Listing 1-6 is essentially the same except for two small differences. The Person2 class
uses the keyword public to declare the name and the gender data elements. The Person2 class uses encapsulation
the same way the Person class uses. However, data elements name and gender are not hidden. That is, the Person2
class does not use data hiding (Data hiding is an example of information hiding). If you look at the constructor and
methods of Person and Person2 classes, their bodies use information hiding because the logic written inside their
bodies is hidden from their users.
encapsulation and information hiding are two distinct concepts of object-oriented programming. the existence of
one does not imply the existence of the other.
Tip
Inheritance
Inheritance is another important concept in object-oriented programming. It lets you use abstraction in a new way.
You have seen how a class represents an abstraction in previous sections. The Person class shown in Listing 1-1
represents an abstraction for a real-world person. The inheritance mechanism lets you define a new abstraction by
extending an existing abstraction. The existing abstraction is called a supertype, a superclass, a parent class, or a base
class. The new abstraction is called a subtype, a subclass, a child class, or a derived class. It is said that a subtype is
derived (or inherited) from a supertype; a supertype is a generalization of a subtype; and a subtype is a specialization
of a supertype. The inheritance can be used to define new abstractions at more than one level. A subtype can be
used as a supertype to define another subtype and so on. Inheritance gives rise to a family of types arranged in a
hierarchical form.
 
 
Search WWH ::




Custom Search