Inheritance: C# vs Java

Hi. I’m quite new with Unity and C# but I have previous experience with Java programming (yes Java, not JavaScript). I’m trying to create a “Destructibles” -class which contains functionality for all destructible objects. Now let’s say I have the following piece of code:

public class Destructible : MonoBehaviour {

public float currentHealth;

public Destructible() {
//this is empty
}

public void TakeDamage(float damage) {
currentHealth -= damage;
}

And a class which inherits this:
public class PlayerHealth : Destructible {

public float currentHealth;

public PlayerHealth() {
//this is empty
}

public void TakeDamage(float damage) {
currentHealth -= damage;
}

Now if I remember correctly, this would work just fine in Java (in principle), but when I try this in C#, Unity gives me a following error message: “The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(MonoBehaviour) currentHealth”. Isn’t it the idea of inheritance to being able to use the parent’s script as a base for multiple child classes? If so the what is the point of not being able to use item names with them?

You have an example of “shadowing” in Java here. You are declaring a variable with the same name in base and sub class. Which currentHealth gets referenced would depend on which type our reference to currentHealth goes through. In your example the currentHealth of the subclass is not inherited; it’s a completely new variable in the subclass.

This is not possible in C# but it doesn’t mean inheritance is somehow broken in C#. Variable shadowing is just a small, at times confusing, added functionality of inheritance. Like @Positive7 says, you just declare each variable just once at the base-most level of inheritance where you need it to be available and it will become a variable in all subclasses too as long as its access modifier is relaxed enough (protected / public).

EDIT: it is possible to hide base class members with the “new” keyword but this is not quite the same as “shadowing”

There’s no difference in Java and C# in this basic form of variable inheritance. You could declare currentHealth only in the base class and then reference currentHealth of both sub or base class instances in both Java and C#.

Thanks guys! I’ll look into this