• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

variables in inteface

 
Anjali Vaidya
Ranch Hand
Posts: 40
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pramod P Deore
Ranch Hand
Posts: 632
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Stephan van Hulst
Bartender
Pie
Posts: 6128
74
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Piyush Joshi
Ranch Hand
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic