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.
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


Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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: 632



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

Joined: Sep 20, 2010
Posts: 4094
    
  18

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.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: variables in inteface
 
It's not a secret anymore!