简体   繁体   中英

base and derived classes

If I have Person class which will handle all common properties

Person.cs

public class Person
{
   public FirstAndLastName {get; set;}
   public Health Health {get; set;}
   public Personality Personality {get; set;}
}

now I will need Player objects and later on different types of players (soccerPlayer, bballplayer, etc.) Since player is a person can I use this approach

Player.cs
public class Player:Person
{
   public Sport Sport {get; set;}
}

Now I want to implement some sport based player unique properties like: in basketball alley up , or volley shoot in football (soccer). You've got the pic.

Basketball.cs
public class Basketball:Player
{
   public int AlleyUpLevel {get; set;}
}

Question: is this proper way of creating base and derived classes, should my basketball player have access to all properties defined in Person class ? Thanks

This is the correct way to create base and derived classes. Because your class Basketball inherits from Player which inherits from Person , Basketball will indeed have access to everything defined in Person that is marked public or protected . Anything marked private will not be accessible to inheriting classes. Also keep in mind that in the case of many constructs such as fields and methods, the lack of an access modifier will default to a private access level.

Since your properties are all public , anyone , not just those deriving from Person , has access to both getting and setting the value of the property.

You could consider making the setter private or protected , as in

public Personality Personality { get; protected set; }

The keyword protected means "only access from the containing class and from classes deriving from the containing class". On the other hand private means "only access from the containing class/struct".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM