Previous |
Next |
State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships "is a" and "has a".
This is a very basic OO question and you will probably get a
question on it in the exam. Essentially it seeks to find out if you
understand when something is referring the type of class structure
that an object belongs to and when it refers to a method or field
that a class has.
Thus a cat IS A type of animal and a cat HAS a tail. Of course the
distinction can be blurred. If you were a zoologist and knew the
correct names for groups of animal types you might say a cat IS
A
longlatinwordforanimalgroupwithtails.
but for the purpose of the exam this is not a
consideration.
The exam questions tend to be of the type whereby you get a text
description of a potential hierarchy and you get questions as to
what ought to be a field and what ought to be a new class type as a
child. These questions can look complex at first glance, but if you
read them carefully they are fairly obvious.
The Java 1.1 objectives did not specifically mention encapsulation, though you would be hard pressed to study Java and not come across the concept. Encapsulation involves separating the interface of a class from its implementation. This means you can't "accidentally" corrupt the value of a field, you have to use a method to change a value.
Encapsulation involves hiding data of a class and allowing access only through a public interface. |
To do this usually involves the creation of private variables (fields) where the value is updated and retrieved via methods. The standard naming convention for these methods is
setFieldName
getFieldName
For example if you were changing the Color of a shape you might create a method pair in the form
public void setColor(Color c){ cBack = c; } public Color getColor(){ return cBack; }
The main access control keywords for variables are
public
private
protected
Do not be mislead into thinking that the access control system is to do with security. It is not designed to prevent a programmer getting at variables, it is to help avoid unwanted modification.
The standard approach using the Color example above would be for the Color field cBack to be private. A private field is only visible from within the current class. This means a programmer cannot accidentally write code from another class that changes the value. This can help to reduce the introduction of bugs.
The separation of interface and implementation makes it easier to modify the code within a class without breaking any other code that uses it.
For the class designer this leads to the ability to modify a class, knowing that it will not break programs that use it. A class designer can insert additional checking routines for "sanity checks" for the modification of fields. I have worked on insurance projects where it was possible for clients to have an age of less than zero. If such a value is stored in a simple field such as an integer, there is no obvious place to store checking routines. If the age were only accessible via set and get methods it will be possible to insert checks against zero or negative ages in such a way that it will not break existing code. Of course as development continues more situations may be discovered that need checking against.
For the end user of the class it means they do not have to understand how the internals work and are presented with a clearly defined interface for dealing with data. The end user can be confident that updates to the class code will not break their existing code.
Because polymorphism allows for the selection of which version of a method executes at runtime, sometimes it is not obvious which method will be run. Take the following example.
class Base { int i=99; public void amethod(){ System.out.println("Base.amethod()"); } } public class RType extends Base{ int i=-1; public static void main(String argv[]){ Base b = new RType();//<= Note the type System.out.println(b.i); b.amethod(); } public void amethod(){ System.out.println("RType.amethod()"); } }
Note how the type of the reference is b Base but the type of actual class is RType. The call to amethod will invoke the version in RType but the call to output b.i will reference the field i in the Base class.
Consider you have been given the following design
"A person has a name, age, address and sex. You are designing
a class to represent a type of person called a patient. This kind
of person may be given a diagnosis, have a spouse and may be
alive". Given that the person class has already been created,
what of the following would be appropriate to include when you
design the patient class?
1) registration date
2) age
3) sex
4)diagnosis
What will happen when you attempt to compile and run the following code?
class Base { int i=99; public void amethod(){ System.out.println("Base.amethod()"); } Base(){ amethod(); } } public class RType extends Base{ int i=-1; public static void main(String argv[]){ Base b = new RType(); System.out.println(b.i); b.amethod(); } public void amethod(){ System.out.println("RType.amethod()"); } }
1)
RType.amethod -1 RType.amethod
2)
RType.amethod 99 RType.amethod
3)
99 RType.amethod
4)
Compile time error
Your chief Software designer has shown you a sketch of the new Computer parts system she is about to create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is called LinuxPC and one is called WindowsPC. The main difference between the two is that one runs the Linux operating System and the other runs the Windows System (of course another difference is that one needs constant re-booting and the other runs reliably). Under the WindowsPC are two Sub classes one called Server and one Called Workstation. How might you appraise your designers work?
1) Give the go ahead for further design using the current
scheme
2) Ask for a re-design of the hierarchy with changing the Operating
System to a field rather than Class type
3) Ask for the option of WindowsPC to be removed as it will soon be
obsolete
4) Change the hierarchy to remove the need for the superfluous
Computer Class.
Given the following class
class Base{ int Age=33; }
How might you change improve the class with respect to accessing the field Age?
1) Define the variable Age as private
2) Define the variable Age as protected
3) Define the variable Age as private and create a get method that
returns it and a set method that updates it
4) Define the variable Age as protected and create a set method
that returns it and a get method that updates it
Which of the following are benefits of encapsulation
1) All variables can be manipulated as Objects instead of
primitives
2) by making all variables protected they are protected from
accidental corruption
3) The implementation of a class can be changed without breaking
code that uses it
4) Making all methods protected prevents accidental corruption of
data
Name three principal characteristics of Object Oriented programming?
1) encapsulation, dynamic binding, polymorphism
2) polymorphism, overloading, overriding
3) encapsulation, inheritance, dynamic binding
4) encapsulation, inheritance, polymorphism
How can you implement encapsulation in a class
1) make all variables protected and only allow access via
methods
2) make all variables private and only allow access via methods
3) ensure all variables are represented by wrapper classes
4) ensure all variables are accessed through methods in an ancestor
class
1) registration date
4) diagnosis
Registration date is a reasonable additional field for a patient,
and the design specifically says that a patient should have a
diagnosis. As the patient is a type of person, it should have the
fields age and sex available (assuming they were not declared to be
private).
2)
RType.amethod 99 RType.amethod
If this answer seems unlikely, try compiling and running the code. The reason is that this code creates an instance of the RType class but assigns it to a reference of a the Base class. In this situation a reference to any of the fields such as i will refer to the value in the Base class, but a call to a method will refer to the method in the class type rather than its reference handle.
2) Ask for a re-design of the hierarchy with changing the Operating
System to a field rather than Class type
3) Define the variable Age as private and create a get method that returns it and a set method that updates it
3) The implementation of a class can be changed without breaking code that uses it
4) encapsulation, inheritance, polymorphism
I got this question at a job interview once. I got the job.
Can't be certain you will get anything similar in the exam, but
its handy to know.
2) make all variables private and only allow access via methods
This topic is covered in the Sun Tutorial at
http://java.sun.com/docs/books/tutorial/java/concepts/index.html
Jyothi Krishnan on this topic at
http://www.geocities.com/SiliconValley/Network/3693/obj_sec6.html#obj19
Java 1.1 Unleashed
http://www.itlibrary.com/reference/library/1575212986/htm/ch05.htm
(See the section on encapsulation)
Chapter 6 from the Roberts, Heller and Earnest book
http://developer.java.sun.com/developer/Books/certification/page1.html
Previous |
Next |