aspose file tools*
The moose likes Beginning Java and the fly likes same var in parent and child interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "same var in parent and child interface" Watch "same var in parent and child interface" New topic
Author

same var in parent and child interface

Pushkaraj Thorat
Greenhorn

Joined: Jun 07, 2007
Posts: 7
Hi i am using jdk 1.5 and compiling below code, its not giving as there is ambiguity of variable i.

interface a{
public static final int i=3;
public boolean equals1(Object obj);
}
interface b extends a{
public static final int i=30;
}

now First class is implementing b,
Output of this statement : System.out.println(((b)new First()).i);
is coming as 30
and
output of this: System.out.println(((a)new First()).i);
is coming as 3

I feel that it should show a ambiguity error
[ June 29, 2007: Message edited by: Pushkaraj Thorat ]
Ashutosh Limaye
Ranch Hand

Joined: Oct 24, 2005
Posts: 58


...this doesn't give problem why should that?
Pushkaraj Thorat
Greenhorn

Joined: Jun 07, 2007
Posts: 7
Its not class it should be interface.
and in interface all variables are

public static and final

and how come final variables should be allowed to change...
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
This seems to be something which confuses lots of people. See this recent thread. Only that was about classes.

If you have a subclass, any variables with the same name hide the variable in the superclass. You haven't altered i = 3, but only hidden it. The 3 is still there, only you can't find it.
Try this sort of thing:-Then see whether this sort of thing will work, or whether it even compiles at all:-

Try that and tell us what happens.
Pushkaraj Thorat
Greenhorn

Joined: Jun 07, 2007
Posts: 7
hmm I go it
Thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You're welcome.

The reason it won't compile is that you have a conflict in diamond inheritance.Different values of i are inherited by the different routes, and the compiler cannot resolve the conflict.
Pushkaraj Thorat
Greenhorn

Joined: Jun 07, 2007
Posts: 7
But is there any way by which we can access the var 'i' of interface
without creating instance of interface(concrete class) and casting to interface.
[ July 02, 2007: Message edited by: Pushkaraj Thorat ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You could try implementing one interface with an inner class . . .

But it will get you thrown out of the beginners' forum.

Anybody else got any ideas?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: same var in parent and child interface