Mahesha Padyana
Mahesha Padyana

Reputation: 431

Two subclasses Sharing only one instance of super class variable

I have one Bicycle class that is parent. I want to have two sub classes for front wheel and back wheel. Is there any way I can create only one instance of super class and then create two separate instances of sub classes that share only one instance of the super class. Basically bicycle is one, but wheels are two and hence common variables of bicycle must be instantiated only once. I would like to go for IS-A relationship so that I can re-use many variables and methods. Also I cannot use static here because each bicycle is different instance.

Ex:

class Bicycle {
    String name;
    int year;
    double price;
}

class FrontWheel extends bicycle {
    double wheelSize;
}

class BackWheel extends bicycle {
    double wheelSize;
}

In main program, if I create instances of FrontWheel and BackWheel, obviously two sets of common variables (year, name etc) are getting created right. Is there anyway to avoid duplication of memory allocation for common variables? Any other options available in Java?

Upvotes: 0

Views: 536

Answers (2)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

Inheritance depicts IS-A relationship in terms specialization. A Special bicycle could be inherited from Bicycle but Wheel cannot be specialization of a bicycle.

class FrontWheel; // forward declaration
class BackWheel ; // forward declaration
class Bicycle {
String name;
int year;
double price;
Frontwheel f; // aggregation or composition to be precise
BackWheel b; // aggregation or composition to be precise
}

class FrontWheel  {
Bicycle b; // member of which Bicycle 
double wheelSize;
}

class BackWheel {
Bicycle b; // member of which Bicycle 
double wheelSize;
}

Upvotes: 0

Axarydax
Axarydax

Reputation: 16603

FrontWheel is not a Bicycle, but a Bicycle contains two wheels! This is an example where you use inheritance incorrectly.

You are supposed to have a FrontWheel and BackWheel instances in a Bycicle.

Therefore, for example

class Bicycle {
  String name;
  int year;
  double price;
  Wheel frontWheel,rearWheel;
}

class Wheel{
  protected double wheelSize;
}

Upvotes: 5

Related Questions