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

variables in inteface

Anjali Vaidya
Ranch Hand

Joined: Jan 25, 2011
Posts: 40

hi all!
actually i created a Vehicle interface which has methods engine(),body() and wheels(). Car class and Bike class implement this.
I want to create a variable called color and wheel in Vehicle so that every class which inherits it has these. But unfortunately, I cannot make it. Can anybody please help me in making variables which are used by all the inheriting classes of Vehicle?
Thanks in advance
Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207

Anjali Vaidya wrote:But unfortunately, I cannot make it.

Can you show what have you tried?
and be aware that any field you declare in an Interface is implicitly public,static and final.


Piyush
Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 629



Life is easy because we write the source code.....
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3615
    
  14

You can't, unless they are constants (static and final). Variables are implementation details, so they shouldn't be part of an interface.

Instead, what you can do is create an abstract class AbstractVehicle that implements Vehicle, and give that class the color variable (which should be private) and give it getter and/or setter methods to view or change the vehicles color. These methods are then inherited by Car and Bike, which both extend AbstractVehicle.
Anjali Vaidya
Ranch Hand

Joined: Jan 25, 2011
Posts: 40

Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207



So now you see wheel and colour are implicitly constants so it is
pubilc static final int wheel;
public static final String colour;
So whatever you were trying can not be done this way.

But your requirement can be solved by following what Stephan has explained.
 
jQuery in Action, 2nd edition
 
subject: variables in inteface