2

I have the following class structure:

Class Human, with message("Hello, ")
Class Townsmen extends Human, with message("I live in town.")
Class Merchant extends Townsmen, with message("I'm merchant.")

Is it possible for an instance of Merchant to say "Hello, I'm merchant.", using super calls? I have a program in Java, and the code is much more complex, but the idea is the same. In addition I cannot modify Human nor Townsmen classes.

Perception
  • 79,279
  • 19
  • 185
  • 195
jnovacho
  • 2,825
  • 6
  • 27
  • 44

4 Answers4

3

All I can think of is: Class Merchant extends Human, with message("I'm merchant.")

I don't think you can skip the superclass constructors you don't like - this isn't how inheritance works.

Perception
  • 79,279
  • 19
  • 185
  • 195
executifs
  • 1,138
  • 1
  • 9
  • 23
3

Well, you can hack around using reflection to get what you want (see Why is super.super.method(); not allowed in Java?). However, DONT!

The problem you are facing is solvable using the right design.

As a thumb rule - If you are trying to achieve something very unique that the language itself tries to restrict, probably something is wrong with your design. (my 2 cents ;))

Community
  • 1
  • 1
sgibly
  • 3,828
  • 1
  • 21
  • 21
1

This isn't possible in Java, which doesn't allow multiple inheritance. The correct way to do this would be:

      Human
     /     
  TownMember
  /       \
 Townsmen  Merchant

With TownMember having whatever logic that townsmen has that merchant inherits.

Since you can't do that, you're going to need to have Merchant extend Human and just re-implement that logic.

Jeremy
  • 5,365
  • 14
  • 51
  • 80
  • Multiple inheritance isn't really the issue here. Skipping intermediate superclass implementations however, is. – Perception Aug 13 '11 at 11:53
0

You can have Merchant not call a super method and do what ever the Human.message does. It can use reflections if permissions is a problem.

However it appears that a Merchant is not a Townsman and should extend Human.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130