File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Variables inside Interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables inside Interface" Watch "Variables inside Interface" New topic
Author

Variables inside Interface

Thillai Sakthi
Ranch Hand

Joined: Jun 17, 2000
Posts: 102
I understand that all variables (i.e. data members) inside an interface are final and static. Going by this logic, the following program should throw an error, but works perfectly! Kindly clarify why?
interface inter1
{
int i=10;//i is final?
void dis();
}
interface inter2
{
int i=20; /* Reinitializing i again here. Compiler is expected to throw an error.*/
}
class face implements inter2,inter1
{
public void dis()
{
System.out.println("Interface 1 is called");
}
public static void main(String ar[])
{
face ob=new face();
ob.dis();
System.out.println(inter1.i);
System.out.println(inter2.i);
}
}


------------------

Regards,
Shakthi
deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
hi kumaresan,

look carefully :
1) u are initializing i two times but in two different interfaces. so being in two different interfaces they r not same. so compiler sees them as two different i's. & each of them is initialized once only. so it is perfectly okay.

2) the compiler will certainly give an error if in ur main method of face class u use any of the following statement
inter1.i = 2;
or
inter1.i = 4;
coz now u r trying to alter a final variable.

hope this helps
do let me know ur response
regards
deekasha
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Variables inside Interface