• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner class question from Dan's exam

 
Hemal Mehta
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why doesn't this code compile?
abstract class A {
private int x = 4;
private int y = 2;
public int x() {return x;}
public void x(int x) {this.x = x;}
public int y() {return y;}
public void y(int y) {this.y = y;}
}
interface B {int math();}
class C {
static class D extends A implements B {
public int math() {return x()+y();}
}
static A a1 = new A() implements B{
public int math() {return x()+y();}
};
public static void main(String[] args) {
System.out.print(new C.D().math());
System.out.print(a1.math());
}
}
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for using my exam.
Code is a lot easier to read when it is posted inside of a code block. Just use the "Instant UBB Code" options that are available on the screen used to post messages. In this case, just click the "CODE" button and then paste the code inside of the blocks.


An anonymous class can extend a superclass or it can implement an interface. However, an anonymous class declaration that extends a superclass is not permitted to also have an implements clause. In this case, the anonymous class referenced by a1 attempts to extend class A but a compile-time error is generated due to the "implements" clause.
I hope that helps.
 
Hemal Mehta
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see the anonymous class exteding any class here...
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Hemal Mehta:
I don't see the anonymous class exteding any class here...

The following anonymous class declaration extends class A and overrides method x. This anonymous class declaration is legal.

The following anonymous class declaration implements interface B. This declaration is legal.


The following annonymous class declaration attempts to extend class A and implement interface B. This declaration is not legal because an anonymous class declaration can not have an "implements" clause.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic