Professional Documents
Culture Documents
9.0 Introduction
Encapsulation literally means enclosing many smaller things within a larger outer
cover. Under the cover of a class definition, many data and method members remain
covered. So a class actually encapsulates a good number of variables and methods. The
internal details of a class can be kept hidden from a user by a technique called information
or data hiding. Such information or data hiding is necessary so that user cannot do any
damage or harm to the sensitive data or methods. Moreover, data hiding principle should
allow users to use classes without knowing their inner details.
To achieve such a goal, java provides visibility modifiers or access specifier like
private, public, default (i.e. when not specifier) or protected, etc. The protected specifier
can be applied only to inherited subclasses. A subclass can be derived from a base class
(called superclass) by inheriting the latter’s data and method definitions over which any
further addition of data or function members can be made to fulfil specialized requirements
of the subclass.
This chapter deals with the principles and practice of encapsulation, data hiding and
inheritance.
When a member of a class (data or method) is specified as public, any other class or
external codes can get access to that member. The main () method is always made public so
that run-time classes or codes can have direct access to it. When a member of a class is
specified as private, only other members of its own class and none else can access that
member. By default, that is when no access specifier is explicitly mentioned, the member of
a class will be treated as public within its own package, but cannot be accessed by any
member outside of that package.
To protect your data from unwanted access, you can allow access only through
member methods and specify those members as private or public according to application
requirements. An access specifier is mentioned first in a member’s type specification. For
example --
public int x;
private int method( double a, char b) { ..... }
etc.
Example-9.1 will show how private data variable can be accessed using get () and set ()
methods only.
class AccessVariables
{
int x; // default, so direct access possible
public int y; // public, so direct access possible
private int z; // private,
// so needs methods to access it
// for which methods are defined now
void setz (int j) {
z = j;
}
int getz () {
return z;
}
}
x is = 12
y is = 65
z is = 98
You have noticed that to access the private variable z, the methods getz() and setz() have
been used by the class TestAccess as the variables (x, y, z) were defined in a separate
class AccessVariables. Thus proper access specifier can protect sensitive data and methods.
9.2 Scope & Visibility Rules
The scope rules are the rules by which it is decided how a particular data item
or method can be accessed in a program environment. Visibility is also a related term
used with respect to access control. Visibility is concerned with the question whether a
specified variable can be used from a given place in a program.
* Data declared as instance variables in a class, called global data, can be used by all the
methods belonging to that class.
• Data declared within a method, called local data, can be used only in that method.
• If a local variable having the same name as that of a global variable, then local
variable will hide the global variable.
• Variables declared in a block are visible to every method in that block.
• Variables declared in an inner block are not visible outside that block.
• Variables declared in exterior blocks are always visible to interior blocks.
• A class has only two levels of access -- public or default.
• A subclass (i.e. inherited class) cannot access the private members of the superclass
(i.e. base class).
The scope and visibility rules can be summarized in a tabular form as shown in Table-9.1.
Scope Visibility
-------------------------------------------------------------------------------------------------------------
Public variables, methods &
Classes public visible to all classes
Packages add another level of access control. Classes act as containers of data and
methods, whereas packages act as containers of classes, interfaces and sub-packages. Java’s
smallest unit of abstraction is class. Class members can be of four categories:--
Protected specifier can be used when you want to allow an element to be seen outside
your current package, but only for the classes inherited from the base class or superclass.
The package level access rules can be displayed in the form of a table as shown in Table-9.2.
Normally Java classes remain stored in some named packages. Java includes the import
statement to bring any particular class/es or entire package into visibility of a particular
program. Once imported, a class can be referred directly. Import statement(s) should occur
immediately following the package statement, if any, and before any class defined by users.
The general form of the import statement looks like:
When a package is imported, only those items specified as public in that package
will be made available for users’ programs. Let us now examine one example program
which makes use the java’s IO library package along with one user defined class
Wrap1Demo (example-9.2) that is capable of displaying a given decimal number with its
equivalent binary, octal and hexadecimal representations.
Compile and run this program to see how by entering a decimal integer value, you can have
its equivalent representation (Picture 9.1) in binary, octal and hexadecimal.
Picture 9.1
9.5 Inheritance
To inherit the properties of a base class we have to make use of the keyword extends. We
will now examine how from a superclass (i.e. base class) we can derive a sub-class and can
use both together for problem solving. Study example-9.3 carefully.
void show ()
{
System.out.println (" values of i and j :" + i + " " + j);
}
}
//use of both Base & Derived classes in a class with main() method
If you run this program, the following output will appear on the terminal window ---
/**
Definition of a Base Class
*/
name = fullname;
branch = discipline;
department = dept;
}
/**
* An example of a method
*/
public void setAddress (String road, String city, int pin)
{
hno_road = road;
town = city;
pincode = pin;
}
public void displayDetails() {
System.out.println (pincode);
}
}
/**
* An example of a method
*/
public void setMajor(String major)
{
specialization = major;
}
public void getFullDetails(){
/**
Second level inheritance
*/
public class PGTechStud extends TechStud
{
String thesisName;
String guide;
/**
* Constructor for objects of class PGTechStud
*/
public PGTechStud(String pgsname, String pgsdisp,String pgdept, String
special, String sguide)
{
super ( pgsname, pgsdisp, pgdept, special);
guide = sguide;
}
/**
* An example of a method
*/
public void setThesisName(String thesis)
{
thesisName = thesis;
}
public void allDetails() {
}
}
.
If you run this program, the output will appear on the terminal window as shown in
Picture 9.2 - --
Picture 9.2
Study example-9.4 very carefully to see how from a base class Student, TechStud subclass
is derived as a first level inheritance and then the TechStud is further extended to
PGTechStud as a second level inheritance. The DemoMLinhirit class containing main ()
method controls the members of all the classes as per application requirements.
Please note that library classes present in the java packages can be used as base classes to
derive subclasses as per software requirements. Thus software development becomes easier
and simpler by reuse of library classes either directly or by deriving classes from them
utilizing the inheritance property.
To know more about java’s inheritance properties, you have to consult the Complete
Reference: Java 2.
Interfaces can be used to support dynamic method binding at run time. Java
does not allow Multiple inheritance (i.e. inheriting properties from different base or super
classes instead of from a single base or super class as used in C++). An interface can help
implementing multiple inheritance like features in java, if required at all. Just remember
that java allows only multi-level single inheritance but not multiple inheritance.
Interface can also disconnect the definition of a method or a set of methods from the
inheritance hierarchy and can allow “ one interface, multiple methods” aspect of
polymorphism.
An interface is defined just like a class having a general structural form ---
Once an interface is defined, one or more classes can implement that interface by including
the implement clause in a class definition. The general form of a class which includes the
implement clause looks like ----
Now an example will be show that will implement the stack operations – push & pop – by
taking help of an interface. (See Example-9.5)
interface IntegerStack {
void push(int data);
int pop();
}
/**
* a description of class FixedLenthStack */
/**
* stack initialization
*/
public FixedLenthStack(int size)
{
/**
* Write a description of class DemoInterface here. */
public class DemoInterface
{
public static void main()
{FixedLenthStack stk_1 = new FixedLenthStack(6);
FixedLenthStack stk_2 = new FixedLenthStack(12);
If you run this program, the output will appear as shown below: ----
The output reveals the fact that a stack is having a Last in First out (LIFO) data structure.
9.6 Conclusions
Encapsulation & Data hiding are the two important aspects of the Object Oriented
Programming paradigm. Instance variables and methods, encapsulated within a class, can be
further protected from misuse by using access specifiers like private, public, etc. The topics
have been discussed in details using examples. The scope and visibility rules have been
explained and presented in a tabulated form. The package level access control rules are also
shown in the form of a table.
With appropriate examples, it has been shown how java’s library and predefined user
classes can be imported and used together to construct a new class to fulfil various
application requirements.
The inheritance property of java has been explained with suitable examples. Java
supports only single inheritance but not multiple inheritance like C++. However multi-level
inheritance is very much possible and allowed by java. The importance of java’s interface
has just been touched upon.