permaculture playing cards*
The moose likes Beginning Java and the fly likes interface questions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface questions" Watch "interface questions" New topic
Author

interface questions

Niyas Ahmed Sheikh
Ranch Hand

Joined: Jun 15, 2005
Posts: 129
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

Joined: Jan 19, 2004
Posts: 8
http://forum.java.sun.com/thread.jspa?threadID=398001&messageID=1731551#1731551
Niyas Ahmed Sheikh
Ranch Hand

Joined: Jun 15, 2005
Posts: 129
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

Joined: Jul 22, 2000
Posts: 9046
    
  10


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)


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Niyas Ahmed Sheikh
Ranch Hand

Joined: Jun 15, 2005
Posts: 129
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

Joined: Oct 24, 2000
Posts: 119
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


Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
 
GeeCON Prague 2014
 
subject: interface questions