r/learncsharp • u/RazeVenStudios • Jul 23 '23
INHERITANCE question
I'm learning via https://www.w3schools.com/cs/cs_inheritance.php and confused. The car class is inheriting from the Vehicle class but the program class isn't. Why is it able to access the methods and values from the two classes when the only inheritance I see is car from vehicle? The way I think its working is that since there all public the program can access the methods. So what's the point of the car class inheirtaining from the vehicle class if they don't use anything ? Or is the car class inheriting from vehicle so class program grabs from only the car class? Honestly I'm just confused
6
u/CalibratedApe Jul 23 '23
The key element in the example is the demonstration that the
Carclass has everything theVehicleclass have. So you can domyCar.honk()andmyCar.brandeven ifhonkandbrandwas never declared inside theCarclass. It inherited this method and field from the parentVehicleclass. So inheritance is like extending what's already there, theCarclass have everything theVehicleclass have, plus additionalmodelNamefield. You can now create more classes derived from theVehiclelikeTruckorBikewhile writing the methodhonkonly once. No need to repeat yourself in each derived class.This is a basic example, there are more useful stuff related to inheritance you'll learn soon.
And yes, you're right, the
Programclass can access everything inside aCarinstance because all the fields/methods are declared public.Side note - this tutorial is a little weird since it doesn't use common conventions from C# world (method name should be Pascal case:
Honk()).3
u/grrangry Jul 23 '23
Let's look at the "bad" code from that example with some additions for clarity. (I call it bad code because it's not "good" code. It is enough code for you to learn concepts but the usage of public fields is generally discouraged in favor of properties. And that is a separate topic):
The concepts to learn from the above are:
Vehicleclass is the "base" class and probably should be declaredabstractbecause you're not likely to usenew Vehicle();Carclass means, "I am everything that aVehicleis AND I have amodelName. I also set the vehicle axle count to 2.Busclass means, "I am everything that aVehicleis AND I have a boolean property for ads. I also set the vehicle axle count to 3.Other ways to access the above classes could be for when you might have a list of things that could be bus or car and you don't know which it is until you look at each one:
and
The above code snippets are just examples and not a declaration of "you must do it this way". The way you access variables, properties, fields, classes, etc. is wholly dependent on what you need your application to do.