*
The moose likes Beginning Java and the fly likes Instance variables in interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Instance variables in interface" Watch "Instance variables in interface" New topic
Author

Instance variables in interface

Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
Hi,

Why is it valid to declare instance variables in java interfaces?
Not sure if this question makes any sense....

Thanks,
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

You can't.

Any "field" you declare in an interface will be a public static final field. In other words, a constant.

Try making it protected, it will fail because it would become protected static final, which is not allowed inside interfaces.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
Hi Rob,

I wrote an example. This code compiles fine.



Please clarify?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Here's what the Java compiler makes of that code:

Every field in an interface is public, static and final, even if you omit one or more of the modifiers.

Every method in an interface is public and abstract, even if you omit one or more of the modifiers.
Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
Got It Rob.

Thanks
ben stone
Greenhorn

Joined: Oct 04, 2007
Posts: 3
I was asked by someone why Interface variables are made public static final by default by Java Language Designers. Could someone explain this.

Thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Because anything else is part of the implementation, and interfaces cannot contain any implementation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Instance variables in interface
 
Similar Threads
Garbase Collection
Static Blocks
Variables in Java
Youtube embed
static block