A Closer Look at Methods and Classes Flashcards

1
Q

Given this fragment,

class X {
private int count;

is the following fragment correct?
class Y {
public static void main(String[] args) {
X ob = new X();

ob.count = 10;
A

No; a private member cannot be accessed outside of its class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

An access modifier must __________ a member’s declaration.

A

precede

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

The complement of a queue is a stack. It uses first-in, last-out accessing and is often likened to a stack of plates. The first plate put on the table is the last plate used. Create a stack class called Stack that can hold characters. Call the methods that access the stack push( ) and pop( ). Allow the user to specify the size of the stack when it is created. Keep all other members of the Stack class private. (Hint: You can use the Queue class as a model; just change the way that the data is accessed.)

A

// A stack class for characters.
class Stack {
private char[] stck; // this array holds the stack
private int tos; // top of stack

// Construct an empty Stack given its size.
Stack(int size) {
stck = new char[size]; // allocate memory for stack
tos = 0;
}

// Construct a Stack from a Stack.
Stack(Stack ob) {
tos = ob.tos;
stck = new char[ob.stck.length];
// copy elements
for(int i=0; i < tos; i++)
stck[i] = ob.stck[i];
}

// Construct a stack with initial values.
Stack(char[] a) {
stck = new char[a.length];

for(int i = 0; i < a.length; i++) { 
  push(a[i]);
}   }

// Push characters onto the stack.
void push(char ch) {
if(tos==stck.length) {
System.out.println(“ – Stack is full.”);
return;
}

stck[tos] = ch;
tos++;   }

// Pop a character from the stack.
char pop() {
if(tos==0) {
System.out.println(“ – Stack is empty.”);
return (char) 0;
}

tos--; 
return stck[tos];   } }

// Demonstrate the Stack class.
class SDemo {
public static void main(String[] args) {
// construct 10-element empty stack
Stack stk1 = new Stack(10);

char[] name = {'T', 'o', 'm'};

// construct stack from array
Stack stk2 = new Stack(name); char ch;
int i;

// put some characters into stk1
for(i=0; i < 10; i++)
  stk1.push((char) ('A' + i));

// construct stack from another stack
Stack stk3 = new Stack(stk1); 
 
// show the stacks.
System.out.print("Contents of stk1: ");
for(i=0; i < 10; i++) {
  ch = stk1.pop();
  System.out.print(ch);
}

System.out.println("\n");

System.out.print("Contents of stk2: ");
for(i=0; i < 3; i++) {
  ch = stk2.pop();
  System.out.print(ch);
}

System.out.println("\n"); 
System.out.print("Contents of stk3: ");
for(i=0; i < 10; i++) {
  ch = stk3.pop();
  System.out.print(ch);
}   }  } Here is the output from the program: Contents of stk1: JIHGFEDCBA Contents of stk2: moT Contents of stk3: JIHGFEDCBA
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Given this class,

class Test {
int a;
Test(int i) { a = i; }
}

write a method called swap( ) that exchanges the contents of the objects referred to by two
Test object references.

A

void swap(Test ob1, Test ob2) {
int t;

t = ob1.a;
ob1.a = ob2.a;
ob2.a = t;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Is the following fragment correct?

class X {
int meth(int a, int b) { … }
String meth(int a, int b) { … }

A

No. Overloaded methods can have different return types, but they do not play a role in overload
resolution. Overloaded methods must have different parameter lists.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a recursive method that displays the contents of a string backwards.

A

// Display a string backwards using recursion.
class Backwards {
String str;

Backwards(String s) {
str = s;
}

void backward(int idx) {
if(idx != str.length()-1) backward(idx+1);

System.out.print(str.charAt(idx));   } }

class BWDemo {
public static void main(String[] args) {
Backwards s = new Backwards(“This is a test”);

s.backward(0);   } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

If all objects of a class need to share the same variable, how must you declare that variable?

A

Shared variables are declared as static.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why might you need to use a static block?

A

A static block is used to perform any initializations related to the class, before any objects are created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is an inner class?

A

An inner class is a nonstatic nested class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

To make a member accessible by only other members of its class, what access modifier must be used?

A

private

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

The name of a method plus its parameter list constitutes the method’s __________.

A

signature

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

An int argument is passed to a method by using call-by-__________.

A

value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Create a varargs method called sum( ) that sums the int values passed to it. Have it return the result. Demonstrate its use.

A

There are many ways to craft the solution. Here is one:

class SumIt {
int sum(int … n) {
int result = 0;

for(int i = 0; i < n.length; i++)
  result += n[i];

return result;   } }

class SumDemo {
public static void main(String[] args) {

SumIt siObj = new SumIt();

int total = siObj.sum(1, 2, 3);
System.out.println("Sum is " + total);

total = siObj.sum(1, 2, 3, 4, 5);
System.out.println("Sum is " + total);   } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Can a varargs method be overloaded?

A

Yes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Show an example of an overloaded varargs method that is ambiguous.

A

Here is one example of an overloaded varargs method that is ambiguous:

double myMeth(double … v ) { // …

double myMeth(double d, double … v) { // …

If you try to call myMeth( ) with one argument, like this,

myMeth(1.1);

the compiler can’t determine which version of the method to invoke.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Using the code from Try This 8-1, put the ICharQ interface and its three implementations into a package called qpack. Keeping the queue demonstration class IQDemo in the default package, show how to import and use the classes in qpack.

A

To put ICharQ and its implementations into the qpack package, you must separate each into its own file, make each implementation class public, and add this statement to the top of each file.

package qpack;

Once this has been done, you can use qpack by adding this import statement to IQDemo.

import qpack.*;

17
Q

What is a namespace? Why is it important that Java allows you to partition the namespace?

A

A namespace is a declarative region. By partitioning the namespace, you can prevent name collisions.

18
Q

Typically, packages are stored in __________.

A

directories

19
Q

Explain the difference between protected and default access.

A

A member with protected access can be used within its package and by a subclass in other packages.

A member with default access can be used only within its package.

20
Q

Explain the two ways that the members of a package can be used by other packages.

A

To use a member of a package, you can either fully qualify its name, or you can import it using import.

21
Q

“One interface, multiple methods” is a key tenet of Java. What feature best exemplifies it?

A

The interface best exemplifies the one interface, multiple methods principle of OOP.

22
Q

How many classes can implement an interface? How many interfaces can a class implement?

A

An interface can be implemented by an unlimited number of classes. A class can implement as many
interfaces as it chooses.

23
Q

Can interfaces be extended?

A

Yes, interfaces can be extended.

24
Q

Create an interface for the Vehicle class from Chapter 7. Call the interface IVehicle.

A

interface IVehicle {

// Return the range.
int range();

// Compute fuel needed for a given distance.
double fuelneeded(int miles);

// Access methods for instance variables.
int getPassengers();
void setPassengers(int p);
int getFuelcap();
void setFuelcap(int f);
int getMpg();
void setMpg(int m);
}

25
Q

Variables declared in an interface are implicitly static and final. Can they be shared with other parts of a program?

A

Yes, interface variables can be used as named constants that are shared by all files in a program.
They are brought into view by implementing their interface.

26
Q

A package is, in essence, a container for classes. True or False?

A

True.

27
Q

What standard Java package is automatically imported into a program?

A

java.lang

28
Q

What keyword is used to declare a default interface method?

A

default

29
Q

Is it possible to define a static method in an interface?

A

Yes

30
Q

Assume that the ICharQ interface shown in Try This 8-1 has been in widespread use for several years. Now, you want to add a method to it called reset(), which will be used to reset the queue to its empty, starting condition. How can this be accomplished without
breaking preexisting code?

A

To avoid breaking preexisting code, you must use a default interface method. Because you can’t know how to reset each queue implementation, the default reset() implementation will need to report an error that indicates that it is not implemented. (The best way to do this is to use an exception. Exceptions are examined in the following chapter.) Fortunately, since no preexisting code assumes that ICharQ defines a reset() method, no preexisting code will encounter that error, and no preexisting code will be broken.

31
Q

How is a static method in an interface called?

A

A static interface method is called through its interface name, by use of the dot operator.