• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface questions

 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I know we can't create an object for an interface. But the I am very confused with the flow of the below program.

[CODE]
class A{}
class B extends A implements E{} //line 1
class C extends A{}
class D extends B{}
interface E{}

public static void main(String args[])
{
A a = new D(); //line 2(I know this, we creating the subclass
object with super class refernce)
C c = new C(); //line 3

E e = (E)a; // line 4 (What we are doing in this step)
B b = (B)e; // line 5 ( - do - )
}
}

To select:
a. The code compiles without error and runs fine.
b. Compilation error on line 1 because interface E is not yet declared(forward-referencing)
c. The cast on the line 4 is mandatory
d. The cast on the line 5 is not mandatory.

What is forward-referencing?
 
Anand Bala
Greenhorn
Posts: 8
 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bala. But I think I need more help regd to my question. As for as, forward referencing, I learnt it is not possible to have forward reference for variables, but we can have for methods. Any other details or coding regd this.

Note: Alos please answer my question related to the pgm given.
 
Marilyn de Queiroz
Sheriff
Posts: 9061
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Line 4: Unnecessary cast since 'a' "is-a" E slready.
The correct answer is "a. The code compiles without error and runs fine." (if you put the main() method inside a class as I have done)
 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

Thanks for the reply.
So if we want to check whether the cast is necessary or not, we have to check the "is-a" condidtion. Am I right?
 
Philip Heller
author
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Niyas wrote, "So if we want to check whether the cast is necessary or not, we have to check the "is-a" condidtion. Am I right?"

Yes!

(Much more on converting & casting in Chapter 4 of "Complete Java 2 Certification".)

-- Phil
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic