Author Topic:   Nested class
Anju Rao
ranch hand
posted March 07, 2000 08:05 PM         

Following are the two questions from Barry Boone's Mock test.
1) class A {
protected int i;
A(int i) { this.i = i; }
}
which of the following will be a valid inner class for this class? select all valid answers.
a) class B{}
b) class B extends A{}
c) class B
{
B()
{ System.out.println("i="+i);
d) class B{class A{}}
e) class A{}

My Answer: a & c. But i saw in a previous post that the answer is b) also. Can a nested class extend the outer class?

This is the first question of the Barry Boone's test (i have a paper copy of this). I would appreciate if anybody could let me know where the answers for this test are. The only clue i have is that the previous link ended with JavaCert2.html.

Thanks,

maha anna
bartender
posted March 07, 2000 08:31 PM             
Here answer b) is NOT CORRECT but not for the reason you mentioned. An inner class can extend any class as long as the 'extended class' is accessible . The outer class A does not have the default constructor. So class B CAN NOT extend it. If A(){} would have been defined, then ans b is also correct.
regds
maha anna

Joe Java
ranch hand
posted March 07, 2000 08:41 PM             
I thought I had read somewhere or ran across it in an mock test that an inner class could not extend an outer class and then I came across something else that said you could. After reading your post, I had the brilliant idea of writing some code to test it:

class TestInner {
public static void main(String args[]) {
new TestInner().new TestInner2().printSomething();
new TestInner.TestStaticInner().printSomething();
}

void printSomething() {
System.out.println("TestInners print");
}


class TestInner2 extends TestInner {
void printSomething() {
System.out.println("Inner class print");
super.printSomething();
}

}

static class TestStaticInner extends TestInner {
void printSomething() {
System.out.println("Static inner print");
}

}

}
This code compiles and runs successfully on my 1.2 JVM so I guess you can extend an outer class in an inner class. But then I have to ask in what situation would one want to do this?

hey, i just got promoted to ranch hand, does that mean i'm certified now?

[This message has been edited by Joe Java (edited March 07, 2000).]

shan
unregistered
posted March 07, 2000 08:46 PM           
I feel c is also wrong for the same reason mentioned by Anna

maha anna
bartender
posted March 07, 2000 09:58 PM             
shan,
ans c) has got some typo. The braces do not match. If that is corrected then ans c) is PERFECTLY correct.
regds
maha anna

Jim Yingst
sheriff
posted March 07, 2000 10:11 PM             
Shan- the difference is, in c) class B does not extend A as it does in b). Since it doesn't extend A, it doesn't try to call new A() as a default super-constructor, so there's no problem. c) is correct.

Anju Rao
ranch hand
posted March 08, 2000 09:03 AM         
Thanks for your replies. Appreciate it.

|