
Java 1.1 Certification Training Guide
by Cary A. Jardin, Cary JardinOverview
This Exam Guide prepares readers for the two official Sun Java certification exams. Book/CD ROM set contains more than 20 practice tests based on real Sun proctored exams. The practice tests on the CD ROM give the reader automated grading and results. Contains complete coverage of Java 1.2 and all the related technologies that a Java developer has to understand in order to pass the exams
- Covers both of Sun s Java certification programs: Java Programmer Certification, and Java Developer Certification
- Author Cary Jardin is working closely with Sun to write this Exam Guide our book will be written using actual, proctored exams from Sun
- Only other way to get this information is to take a series of 3 classes from Sun--in Mountain View, CA for $3,800
Editorial Reviews
Product Details
- ISBN-13:
- 9780789713902
- Publisher:
- Que
- Publication date:
- 03/01/1998
- Edition description:
- BK&CD-ROM
- Pages:
- 605
- Product dimensions:
- 7.59(w) x 9.47(h) x 1.84(d)
Read an Excerpt
[Figures are not included in this sample chapter]
Java 1.1 Certification Training Guide
- 3 -
Java Objects and Exceptions
One of the stranger things about C/C++ is the ability to write pure C code, butcall the code objectized. That is, the primary feature that C++ added to Cwas object support. However, C++ is backwards-compatible with C. In this way, youcould write non-objectized code, run it through a C++ compiler, and call it C++.This is not the case with Java.
In Java everything is an object. If you want to create a simple program to say"Hello World," you have to create an object which encapsulates the program.For example, the following is a simple "Hello World" program.
public class helloWorld{ public static void main(String args[]) { System.out.println("Hello World"); }}
The above declares a class, or object, named helloWorld, inwhich the only method of the class displays the string Hello World. Thismight seem like a meaningless example, but the point is that everything in Java isan object.
- Object declarations and usage
- Casting between objects
- Java exceptions
- Specific knowledge of the reserved words class, extends, publi c, private, protected, final, throw, and throws is required for this chapter and can be found in Chapter 2, "Java Language Internals."
- 1. What modifier would be used to limit a method's visibility to only the currently defined class?
- A. public
B. private
C. protected
D. static
2. What modifier would be used to limit a method's visibility to only the other classes and subclasses in the current package?- A. public
B. private
C. protected
D. static
- A. public
Answers are located at the end of the Chapter...
Java Objects
OBJECTIVE Java is an object-oriented language. Knowing how to declare anduse objects is vital to development and required knowledge for the Certified ProgrammerExamination.
Unlike most concepts in computer science that you can point to and say, "This.This is what it looks like," objects are slightly more elusive. Java's essencelies in object technology; mastering Java requires comprehensive knowledge of objectsand the object-oriented paradigm.
Almost every programming language has the notion of a grouping of data elements.For example, Pascal supports a record, C supports a struct, anddatabase-centric languages, such as Delphi, PowerBuilder, and Visual Basic, utilizer ecords in a database table. Each of these examples serves the common purpose ofgrouping together pieces of information into a single device. Once the device iscreated, or formed, the device can be referenced as a single element all to itself,and each element it contains can likewise be referenced individually. This type ofdata element grouping is generally referred to as data encapsulation.
Data encapsulation is the cornerstone of Object theory, but objecttheory takes data encapsulation to the next step. That is, encapsulating a groupof data elements into a single entity provides one-stop access to the stored information.Above and beyond the access of data elements, an object has the ability to storecode to access, modify, and present the stored information. The following exampleprovides a simple object, or class, for the storage of personal weight information.
public class myWeight{ public int weight; public int goalWeight; public int numberOfPoundsLeft;}
The class in this code encapsulated three separate elements of information intoa single unit named myWeight. Everything in the above example could be facilitatedwithout the use of any object-oriented methodologies. However, the following exampleuses an object's ability to encapsulate code and data into a single element.
public class myWeight{ public int weight; public int goalWeight; public int numberOfPoundsLeft; public String lostWeight(int howMuch){ weight -= howMuch; numberOfPoundsLeft -= howMuch; if(numberOfPoundsLeft <= 0) retu rn "You Did IT!!!!"; else return "Keep on going. Only " + numberOfPoundsLeftÂ+ " pounds left."; } public String gainedWeight(int howMuch){ weight += howMuch; numberOfPoundsLeft += howMuch; return "The point of this is to LOOSE weight!"; }}
As you can see from the previous example, objects allow data and code to be encapsulatedinto a single entity, which leads directly into the accepted definition of an object:A single extensible, reusable, self-contained unit of data and code encapsulation.
Declaring a Class
Declaring a class in Java is very straightforward, and requires little more thansome rote memorization. The following declares a class named firstClasswhich extends Object.
public class firstClass extends Object{}
As you can see, there are three pieces of the class declaration, beginning withthe reserved word public and ending with Object. The followingdiagrams and defines each of the key elements of a class declaration.
- Class Visibility and Access--public, protected, default, or final
- Class Naming--firstClass
- Class Inheritance--final, extends Object
Class Visibility and Access
OBJECTIVE Firm understanding of Java's method and object visibility modifiersis required knowledge for the Certified Programmer Examination.
In Chapter 2, the concept of class visibility was discussed, but only at preliminarylevel. Drilling down deeper into the subject of class visibility, you need to focuson the two key factors defining the visibility of a class. These are: "Who hasaccess to use the class?", and "Who has access to inherit the class's properties?".The answers to these questions lie in the complete understanding of the four visibilitymodifiers: public, private, protected, and default. Table3.1 provides a quick overview of each of the supported class visibility modifiers.Table 3.1
Table of class visibility modifiers.
Modifier | Visibility |
public | Unrestricted |
protected | Accessible only from within the package, but extensible anywhere |
default | Accessible and extensible only from within the package |
private | Accessible only from within declared class file |
The first and most unrestricted class visibility modifier is public.Classes that are declared as public have no restrictions on visibility andusage. For example, the following example declares a public class namedm yPublicClass.
public myPublicClass{ public int useMe;}
Declaring the myPublicClass class as public allows the classto be extended, as demonstrated below.
public myNewPublicClass extends myPublicClass { public int useMe;}
Likewise, public classes have unrestricted access, as the example demonstrates.
public myTestClass { public myPublicClass useMe;}
The protected and default modifiers offer varying degrees of visibilityfor declared classes. Both these modifiers rely on the concept of packages whichwill be covered later in this chapter. For now, Table 3.1 provides a sense of whatthese two modifiers offer; this information will be expanded upon later.
Lastly, the private modifier forbids other classes from sub-classing,or using the defined class.
Class Inheritance
The concept of data encapsulation was discussed earlier in this chapter, as wellas the standard object facilities. One of the most important concepts to understandis that an object's ability to encapsulate information and code into a single entityprovides the mechanism for object inheritance.
Inheritance is a concept everyone is familiar with. As human-beings we inherita legacy of generic characteristics from previous generations. Eye color, hair color,height, and even weight are inherited from your parental genetic code. Likewise,your parents' genetic code was inherited from their parents, and so on. In this way,a hierarchy of genetic characteristics is constructed.
In Java, an object is the product of prior generations. However, to avoid the"chicken and the egg" problem, you should know that all Java objects arethe product of the java.lang.Object class. That is, all Java-created classeshave at least one parent class, which is Object. The following providesa list of the characteristics which are inherited by all Java classes.
Public Methods of java.lang.Object:
- Object clone() Creates a copy of the current class.
- boolean equals(Object) Checks to see if the passed class reference is equal to the current class.
- void finalize() Specifies a method to be performed when this class is garbage collected.
- Class getClass() Returns the java.lang.Class object of this class.
- int hashCode() Returns a hashcode for this class. This method is used with the java.util.Hastable class.
- void notify() otifies a single waiting thread on a change in condition of another thread. This method will be covered in depth in Chapter 5, "Java API."
- void notifyAll() otifies all of the threads waiting for a condition to change. This method will be covered in depth in Chapter 5.
- String toString() Returns a string that represents the value of this object.
- void wait() Waits to be notified by another thread of a change in this class. T his method will be covered in depth in Chapter 5.
- void wait(long) Waits to be notified by another thread of a change in this class, or the specified time has elapsed. This method will be covered in depth in Chapter 5.
- wait(long,int) Waits to be notified by another thread of a change in this class, or the specified time has elapsed. This method will be covered in depth in Chapter 5.
Listing 3.1 provides a demonstration of object inheritance. In this example, aset of three standard banking functions are formed into a objectized representation.Located in the source are comments describing each piece of functionality. Listing3.1 Class inheritance
//Base Class holds the amount
class transaction{
public int amount;
public transaction(int Amount){
amount = Amount;
}
}
//Withdraw inherits transaction
class withdraw extends transaction{
public int from;
//Overrides base constructor
public withdraw(int Amount, int From){
super(Amount);
from = From;
}
}
public class bankApp{
public static void main(String args[]) {
//Create a new withdraw object
withdraw W = new withdraw(78,2);
//print the Amount
sysytem.out.println("The Amount is " + W.amount);
//print the From Account
sysytem.out.println("From Account " + W.from);< /TT>
//print the Amount
sysytem.out.println("The Objects String " + W.toString());
}
}
Figure 3.1 provides an object diagram of the classes formed in Listing 3.1. Noticehow transaction class inherits all of Object's public members,and likewise withdraw inherits all of Object's and transaction's members.
Figure 3.1 Complete class structure diagram for Listing 3.1.
In spite of this inheritance, it is not beneficial to allow future generations accessto internal support functions. For this reason, Java provides a set of member modifierswhich restrict inheritance and usage. For example, Listing 3.1 declares all membersas public to ensure complete inheritance and usage. The following list providesa detailed description of each of these modifiers.
- public The public modifier specifies full inheritance and usage rights to all accessing and inheriting classes.
- private Almost an exact opposite of the public modifier, the private modifier is only accessible to other members of the current class. That is, a member that is declared as private does not exist for any class other than the current class.
- default The default modifier, referred to as "package," only allows classes in the current package access to specified members.
- final The final modifier forbids any future generations from overriding the specified member.
Constructors and Creation Order
Look back to Listing 3.1 and find the method named transaction in thetransaction class. As you can see, this method is used to initialize theinitial value of the amount member. More generally, the transaction methodis called an object constructor. That is, an object constructor is a methodthat is called when a new instance of an object is created.
An object is a single autonomous entity which contains specific, contextual information.For example, the following object encapsulates a single employee's data file.
public class employee{ public int numMonthWithCompany; public boolean newHire;}
The numMonthWithCompany denotes the total number of months the employeehas been with the company. Also, the newHire field flags the existence ofa new employee. With this implementation, external code will need to accompany theobject in order to properly set the newHire flag. However, the followingexample utilizes an object constructor to set both the numMonthWithCompanyand the newHire flag.
public class employee{ public int numMonthWithCompany; public boolean newHire; //The following is the constructor, //which will be called when a new instance //of the object is created. public employee(int Months){ newHire = Months == 0; numMonthWithCompany = Months; }}
Constructors provide the means to adapt an object to its runtime environment.In this way, more generic objects can be c reated which contain the ability to morphthemselves into various configurations based on a specific need. A good analogy toa constructor is the birth of a baby. Upon the baby being "constructed,"or born into the world, sensory input defines its initial condition. Usually, a newbornis so overwhelmed with sensory input that screaming is its normal defined output.However, it might be possible to modify the environment in which the newborn is firstexposed to, in an attempt to modify the screaming behavior. In programming terms,modify the constructor input to change the initial state.
The concept of a child giving birth to its parents sounds inherently strange.However, in some programming languages that is exactly the case, specifically withthe programmatic concept of creation order defining when objects are created, aswell as when their constructors are called.
As shown in Figure 3.2, there is a direct hierarchy of parental objects for everyobject. Also, you can see that each object relies on functionality found in parentalobjects. This being the case, when a new object is created, all supporting parentalobjects must also be created. More concretely, if each object has its own constructor,each object in the hierarchy must execute its constructor whenever a child objectis created. Figure 3.2 illustrates the creation of the defined objects in Listing3.2.
As you can see from Figure 3.2, Java implements a top-down creation policy. Thatis, the top-most parent in the object hierarchy is created first, sequentially followedby each subsequent parent until the bottom-most object is created. This is demonstratedin Listing 3.2
Figure 3.2 Complete class structure diagra m for Listing 3.2. Listing3.2 Class constructionclass SayHello{
public SayHello(String in){
System.out.println(in);
}
}
class Class1{
public Class1(){
System.out.println("Class1");
}
}
class Class2 extends Class1{
public SayHello S = new SayHello("Class2 Member");
public Class2(){
super();
System.out.println("Class2");
}
}
class Class3 extends Class2{
public SayHello SE = new SayHello("Class3 Member");
public Class3(){
super();
System.out.println("Class3");
}
}
public class creationOrder {
public static void main(String args[]) {
Class3 C = new Class3();
System.out.println("All Done");
System.out.println("(press Enter to exit)");
try {
System.in.read();
} catch (Exception e) {
return;
}
}
}
The main body of the code in Listing 3.2 creates a Class3 object. Basedon the top-down policy of Java, the proper creation would be Class1, Class2,and then Class3. The following program output proves this to be the case.Class1Class2 MemberClass2Class3 MemberClass3All Done(press Enter to exi t)
Java creation order policy can be summarized by, "The parent must be createdbefore the child," which makes intrinsic sense based on the order of nature.A child must have parents in order to be born, and a class is guaranteed to haveits parent's resources available upon execution of the constructor.
Implementing Interfaces and Abstract Method
Thus far, the concept of an object has been defined as an encapsulation of dataand code. However, what if you merely want to define an object, but not populatethe encapsulated content? That is, say you are creating a file folder to containimportant documents. You would undoubtedly create a folder for each appropriate heading.Then, as you receive documents you can put them into the predefined folders. In thisway, you are predefining the storage of your information. Java supports the conceptof predefining methods without supplying an implementation.
For example, the following defines a base class named ticTacToe whichdefines three methods. However, no implementation is supplied for any of the threemethods. In this way, the class is defining a mechanism for inherited objects toimplement.
public class ticTacToe{public void X(int pos){} public void O(int pos){}public boolean gameOver(){ return false; }}
This example utilizes the brute force method of declaring a template for futureobjects. Although this approach might work, it is not the most efficient mechanismto achieve the goal. The following code example defines the same object templateusing the abstract and interface definitions.
public abstract class ticTacToe{ public abstract void X(int pos); public abstract void O(int pos); public abstract boolean gameOver(int pos);}public interface ticTacToe{ public void X(int pos); public void O(int pos); public boolean gameOver(int pos);} Both the abstract and interface methods of defining object templatesproduce similar results. However, the two methods contain drastically different sideeffects. Chapter 11, "Creating Java APIs," will discuss the differencebetween the abstract and interface methods of defining object templates.But, in an attempt to summarize a future discussion: A class can inherit only oneclass, but it can implement as many interfaces as it desires.
In many cases, a single object cannot encapsulate all of the various pieces involvedin a solution. More commonly, solutions are grouped into distinct units of objectscalled packages. Each package can contain one or more individual classes.However, a package is a single unit of encapsulated classes.
In Java, a package is a grouping of classes which are commonly used together.On the usage side, a package allows for multiple classes to be imported into a classwith a single import statement. For example, the following imports all of the classesfound in the common Java IO facilities.
import java.io.*;
From the development perspective, a package can define a partition of thought.For example, if you were creating a banking application, you might choose to storeall banking-related classes in a single package. The following defines a class namedwithdraw to reside in the banking package.
package banking;public class withdraw{ public int amount;}
Object Casting
OBJECTIVE Java's dynamically extensible nature requires complete knowledgeof object casting facilities. For this reason, object casting knowledge is requiredfor the Certified Programmer Examination.
Casting, in the typical programmatic usage, refers to the translation betweenone storage device and another. Chapter 2, "Java Language Internals," discussedthe concept of casting from numerical storage devices, such as int and float.Translating 1.00 into 1 is a logical and useful translation of a numeric value. Castingof classes is equally useful and logical, but requires a bit more thought.
Classes are storage devices, just like an int or a float. However,as stated earlier in this chapter, every class contains at least one parent. Thus,the complexity of casting between objects is a function of the number of parentsa class has. For example, Figure 3.3 displays a graph showing two classes sharinga single parent. For each class in the hierarchy there is a separate set of legalcasts.
Figure 3.3 Two classes share a single parent.
In order to simplify and classify the vast commutations and permutations of variousobject castings, Java provides the following two laws governing the actions of objectcasting.- Casting Down
- Casting Up
Casting Down
Casting down refers to the directional casting that narrows the contai ning storagedevice. For example, casting from a long to an int would narrowthe amount of storage required to store the numeric value. When casting objects,narrowing more specifically refers to the narrowing of functionality from a subclassto a parent. Casting down, more appropriately called "unsafe casting,"narrows functionality from a subclass and converts the object into a parental class.
Based on the nature of casting down, not all operations are legal at runtime.For example, the following code defines Class2 and Class3 to sharea common parent.
class Class1{}class Class2 extends Class1{}class Class3 extends Class1{}
The following code example provides an example of each case in which the Class1,Class2, and Class3 could be casted into one another. Granted, notall class hierarchies are this simplistic, nevertheless all down-casting scenarioscan be broken into the following cases.
Always legal:
Class1 mysteryClass = new Class2;Class2 MyClass = (Class2) mysteryClass;
Always legal:
Class1 mysteryClass = new Class3;Class3 MyClass = (Class3) mysteryClass;
Compilation error and never legal:
Class1 mysteryClass = new Class3;Class2 MyClass = (Class2) mysteryClass;
Possibly legal--if and only if "mysteryClass = new Class3;":
Class3 MyClass = (Class3) mysteryClass;
Possibly legal--if and only if "mysteryClass = new Class2;":
Class2 MyClass = (Class2) mysteryClass;
Casting Up
Unlike casting down, casting up is always legal and valid. However, it takes alittle practice to spot an up-casting usage. Revisiting the numerical casts, castingfrom an int to a long is an example of an up cast. Likewise, castingfrom a subclassed class to a parent class is always legal, thus the nickname "safecast."
To demonstrate the classification of up casting operations, the following classesprovide a simplistic class hierarchy. Once again, not all hierarchies will be thissimple, but all can be localized to serve as a model.
class Class1{}class Class2 extends Class1{}class Class3 extends Class2{}
Always legal:
Class2 mysteryClass = new Class2;Class1 MyClass = (Class1) mysteryClass;
Always legal:
Class3 mysteryClass = new Class3;Class1 MyClass = (Class1) mysteryClass;
OBJECTIVE Java's exceptions provide a powerful facility for the trappingand propagation of runtime error. Knowing how to catch, handle, and declare exceptionsis crucial for effective Java development and is required knowledge for the CertifiedProgrammer Examination.
Exceptions
Simply put, an exception is an object that is created to signify an event. Forexample, if at some time a section of code tries to execute a division by zero, anexception will be raised to notify of the error. In this way exceptions provide amechanism for the handling of runtime errors.
Normally, when an object is defined it is assigned a specific name. However, inthe case of exceptions, an object is created before a specific name has been assigned.Think of it as a ball that is thrown into the sky. When the ball is airborne, noone person retains ownership of the ball, and in a sense it is free. But when theball makes its descent to the earth, it can either be caught or plunge to the ground.If it is caught, the ball then is the property of the person who caught the ball.An exception does not possess an owner until the exception is caught, at which timethe exception is handled. Otherwise, the uncaught exception will be propagated tothe calling block of code.
To more fully understand the concept of an exception, it is imperative to analyzethe handling and throwing of exceptions individually.
Handling Exceptions
Revisiting the ball analogy, all exceptions must be caught. Programmatically speaking,"caught" can be defined as a try...catch block. For example, thefollowing code catches an exception, which is thrown by a call to System.in.read().
try { System.in.read();} catch (Exception e) { return;}
Chapter 2, "Java Language Internals," discusses the proper syntax forboth the try and catch facilities. Additionally, Chapter 2 discussesthe use of the finally facility which provides clean-up after a tryblock has been executed. However, for this discussion, the specific point of interestregarding try blocks lies in the how a try block is executed, andthe specific exception which may be thrown.
Program Flow with Exceptions
When a program reaches the try statement, execution continues throughthe course of the supplied statements. In the case of the previous e xample, the statementexecuted inside the try block is System.in.read(). If this statement executeswithout an exception, program execution proceeds to the next line following the try...catchblock. However, if an exception is raised, the statement within the catchblock will be executed. Following the raised exception, program execution will proceedto the next line following the try...catch block.
In the following example, the finally statement is used to execute aclean-up statement after the execution of the try block. Whether an exceptionis raised or not, program execution cannot leave the try...catch block withoutexecuting. The result being that the output bye-bye is guaranteed to beoutput every time the try...catch block is executed.
try { System.in.read();} catch (Exception e) { return;}finally{ System.out.println("bye-bye");}
Handling Specific Exceptions
Thus far, all examples provided have been catching the generic base class forall exceptions named Exception. For example, the following code catchesthe generic Exception.
try { System.in.read();}catch (IOException e){ System.out.println("IO exception");} catch (Exception e) { return;}
This example first attempts to catch the specific IOException thrownby the System.in.read(). In the case that System.in.read() throwsan exception other than the IOException, the generic Exceptionis caught. In this m anner, Java provides the ability to catch specific, contextualexceptions, or provide a generic handler. The following is a list of the standardJava exceptions. Each is thrown to signify a specific event, and each is a subclassof Exception. The following is a complete list of the standard exceptionsthrown by java.lang members provided for example purposes only--they willnot appear on the test.
Throwing Exceptions
Using the reserved word throw, which is specified in Chapter 2, customexceptions and Java-supplied exceptions can be created. In the following example,the method throws an Exception to signify an invalid parameter value. Noticethe parameter passed to the constructor of the Exception object. This parameteris used to provide a textual message explaining the exception, and will be explainedin full in Chapter 5, "Java API."
NOTE The process by which an exception comes into being is called throwing an exception. That is, programmatically Java provides the ability for you to create your own exceptions, or propagate uncaught exceptions. In both cases, the reserved words throw and throws are employed to facilitate the creation and propagation of exceptions.public void doSomeThing(int Value)throws Exception{ if(Value < 0) throw new Exception("Bad Value"); return;}
In the previous example, the method declaration includes the reserved word throws.This signifies to the Java compiler that the defined method can throw an exceptionof type Ex ception. Any number of exceptions can be thrown from a singlemethod. However, all potentially thrown exceptions must be handled by the callingmethod. The following code is an example of how to propagate an uncaught exception.
public void doSomeThing()throws Exception{ try { System.in.read(); // Throws IOException }catch (RuntimeException e){ System.out.println("IO exception"); } //Exception not caught, propagate up the call stack.}
Summary
To many outside the object-oriented world, the idea of storing data and code ina single, accessible device doesn't seem all that important. It isn't until conceptssuch as inheritance and exceptions are presented that the true appreciation of objectscan be assimilated. Java is a true object-oriented language, and in this chapteryou learned why.
As stated in this chapter, everything is an object. Unlike C++, which providesprogrammers the ability to implement non-object solutions, Java requires all to conformto the object-oriented paradigm. Everything from pure data containers to code librariesare encapsulated into objects. The contents of this chapter focused on how to useand create your own objects.
Exceptions provide a facility to handle runtime errors. This chapter discussedexceptions, and how they can be used to inform of and handle various runtime occurrences.Included in this discussion were examples of the try, catch, finally,throw, and throws language facilities.
In Chapter 4, "Threads in the Java Platform," objects will be expa ndedto include threads and multiple objects executing simultaneously. This is not tosay that the knowledge gained from this chapter is just a prelude to Chapter 4. Rather,this chapter contains core testable information. All the concepts and details foundin this chapter constitute a good 60% of the Certified Programmer Examination. Knowingthe information found in this chapter is crucial to successfully passing the CertifiedProgrammer Examination. For this reason, the following exam questions are providedto give samples of what you can expect on the exams, and what to potentially revisit.
Review Questions
- 1. The following code listing contains one error, which is:
public abstract class myClass{ public abstract fun(int Value){}}
A. public abstract class myClass
B. public abstract fun(int Value){}
C. Incomplete class definition
D. Class must contain a constructor- 2. Which answer best describes the following object hierarchy?
class class1{}class class2 extends class1{}class class3 extends class3{}
A. class3's parent class is class2, and class2's parent class is class1.
B. class3's parent class is class2, class2's parent class is cla ss1, and class1's parent is Object.
C. class1's parent class is class2, and class2's parent class is class3.
D. class1's parent class is class2, class2's parent class is class3, and class3's parent is Object.- 3. What modifier would be used to limit a method's visibility to only the currently defined class?
A. public
B. private
C. protected
D. static- 4. What modifier would be used to limit a method's visibility to only the other classes and subclasses in the current package?
A. public
B. private
C. protected
D. static- 5. The following defines an object hierarchy.
class class1{}class class2 extends class1{}class class3 extends class3{}
- When is the following method valid?
public class3 castMe(class1 ref){ return (class3)ref;}
A. Always
B. Never
C. If and only if ref references an class3 object
D. If and only if ref references an class2 object- 6. The following defines an object hierarchy.
class class1{}class class2 extends class1{}class class3 extends class3{}
- When is the following method valid?
public class1 castMe(class3 ref){ return (class1)ref;}
A. Always
B. Never
C. If and only if ref references an class3 object
D. If and only if ref references an class2 object- 7. What is the output of the following try...catch block?
try{ int I; return;}catch(Exception e){ System.out.println("I am Here"); return;}finally{ System.out.println("Hello Nurse!");}
A. Hello Nurse!
B. No output
C. I am Here
D. Depends on the creation of the int I;- 8. The following code contains a single error, which is
public class myClass{ public void testMe(int Value){ t hrow new Exception("Throw ME!"); }}
A. public class myClass{
B. public void testMe(int Value){
C. throw new Exception("Throw ME!");
D. No Error. You are trying to trick me!- 9. A method may only implement a single interface.
A. True
B. False- 10. A method may only extend a single class.
A. True
B. FalseReview Answers
- 1. B
2. A
3. B
4. C
5. C
6. A
7. A
8. C
9. B
10. A
Answers to Test Yourself Questions at Beginning of Chapter
1. B
2. C - Casting Down
Meet the Author
Customer Reviews
Average Review: