This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by chary vangeepuram: Hi, Why can not we declare instance variables in interface ? Why do we have only public static final variables ? Thanks, Chary Vangeepuram
In order to have instance variables of X you need to have an instance of X...you need to be able to instantiate/create X An interface can't be instantiated/created....it can only be implemented by a class.
Joined: Sep 16, 2002
Hi, In interface, we are declaring the common behaviour of implementing classes in the form of methods...Likewise why can't we have common attributes of implementing classes in the form of variables ? I understand we can not instantiate interface..but... Also I would like to understand why non-final static variables are not allowed in interfaces... Thanks, Chary Vangeepuram
Interface: A point at which independent systems or diverse groups interact...
When you think of an interface, you should think of the way that you interact with something. In Java, how do you interact with another object? Most commonly, you invoke methods on that object. Therefore, we have the notion of an Interface. An Interface isn't designed to detail how a class should be implemented. Rather, an interface details how one should interact with an object. What instance variables are defined is really an "implementation detail" and should not be included in the interface. The interface says that you must define method x, but it does not say anything about how you must implement that method and what variables you must use in order to do so. If you want to define common behavior, as well as common members (such as instance variables), you should be thinking about inheritance from another class, not implementation of an interface. Inheritance, unlike implementation of an interface, defines both the behaviors a class demonstrates as well as internal data contained by that class. All fields declared within an interface are implicity public, static, and final to reinforce this notion. The only reason one should be using fields in an interface, in my opinion, is to have constants that are somehow related to the methods defined in that interface. I hope that helps, Corey