0

I want to ask if a class can inherit from one class or other class. For example, I have a class named "Shareholder". Now, a Shareholder can be either a NaturalPerson or a LegalPerson.

I have the 2 classes (NaturalPerson and LegalPerson), but am I able to select one of them in order for a specific Shareholder object to inherit from one of them ?

Thank you

  • Inheritance is probably not the correct representation of the world in this case. Take a look at an [answer I gave](http://stackoverflow.com/a/28155750/4125191) to a double inheritance question. Can you think of a different way to model the relationship? – RealSkeptic Jun 11 '15 at 09:52

3 Answers3

0

Do NaturalPerson and LegalPerson both inherit from a Person class? If so you might consider using a composition approach like:

class Shareholder {
   private Person person;

   // Inject the type of shareholder person
   // when constructing a Shareholder instance
   public Shareholder(Person person) { this.person = person; }

   // Other stuff specific to shareholders
   public getName() { person.getName(); }
}

That way you can inject any type of person and if you later get more "Person"types there is no impact on the code of the Shareholder class.

0

If I understand you correctly you talk here about multiple inheritance, which is not allowed in java. But you can let a LegalPerson as well as a NaturalPerson be a ShareHolder. What you can not do is let a ShareHolder extend NaturalPerson and a LegalPerson at the same time. A class in java can only have one superclass.

Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63
0

If i am correct in assuming that NaturalPerson and LegalPerson are both ShareHolders, then you need to implement this hierarchy in different way. The base class/interface needs to be a ShareHolder, which further can be extended/implemented by a NaturalPerson or a LegalPerson. Try to think about it like a realtime scenario. e.g. All cars are automobile but all automobile can't be cars, they can be truck, bus, etc. In similar manner all NaturalPerson in your case are ShareHolder but all ShareHolder cannot be NaturalPerson, they can be LegalPerson as well.

Ravi Ranjan
  • 740
  • 2
  • 10
  • 31