Home > Mobile >  How to use Parent Class variable name in the Sub Class method
How to use Parent Class variable name in the Sub Class method

Time:11-01

I tried to create simple console application using C#. I want to cover these simple things with my application.

Inside my Team Class have these methods.

  1. A memeber variable - teamName(string)
  2. A memeber variable - noOfPlayers(int)
  3. A constructor fuction 1.it takes 2 parameters and asasigns them to teanName and noOfPlayers respectively.
  4. A member function AddPlayer(count) 1.it takes an integer count as a parameter and increases noOfPlayers by count.
  5. A member function RemovePlayer 1.it takes an integer count as a parameter and tries to decrease onOfPlayers by count. 2.If decreasign makes noOfPlayers negative, then this function simply return false 3.Else decrease noOfPlayers by count and return true.

Inside my Subteam class (inherited from the Team class) have these methods.

  1. A constructor function. 1.It takes 2 parameters teamName and noOfPlayers and calls the base class contructor with these parameters.
  2. A member fucntion ChangeTeamName
    1. it takes a string name as a parameter and changes teamName to name.

In my ChangeTeamName method i need to use name parameter and change name to the teamName. But I don't know how to do that. There for please help me to create this simple application with above task. And Please check other codes are correct or not.

I got these errors when I tried to run program.

1.Severity Code Description Project File Line Suppression State Error CS1061 'Program.Subteam' does not contain a definition for 'onOfPlayers' and no accessible extension method 'onOfPlayers' accepting a first argument of type 'Program.Subteam' could be found (are you missing a using directive or an assembly reference?) ConsoleApp1 C:\Users\Sandanuwan\Desktop\ConsoleApp1\ConsoleApp1\Program.cs 74 Active

2.Severity Code Description Project File Line Suppression State Error CS0122 'Program.Team.noOfPlayers' is inaccessible due to its protection level ConsoleApp1 C:\Users\Sandanuwan\Desktop\ConsoleApp1\ConsoleApp1\Program.cs 68 Active

   namespace ConsoleApp1
    {
    public partial class Program
    {
        public class Team
        {
            string teamName;
            int noOfPlayers;

            public Team(string teamName, int noOfPlayers)
            {
                this.teamName = teamName;
                this.noOfPlayers = noOfPlayers;
            }
            public void AddPlayer(int count)
            {
                noOfPlayers = count  ;
            }

            public  bool RemovePlayer(int count)
            {
                noOfPlayers = count--;
               
                if (noOfPlayers < 0)
                {
                    return false;
                }               
                return true;
            }           
        }

        class Subteam : Team
        {
            public Subteam(string teamName, int noOfPlayers) : base(teamName, noOfPlayers)
            {
               
            }

            public void ChangeTeamName(string name)
            {
                
            }
        }
        static void Main(string[] args)
        {
            if(!typeof(Subteam).IsSubclassOf(typeof(Team)))
            {
                throw new Exception("Subteam class chould inherit from Team class");
            }

            String str = Console.ReadLine();
            String[] strArr = str.Split();
            string initialName = strArr[0];
            int count = Convert.ToInt32(strArr[1]);
            Subteam teamObj = new Subteam(initialName, count);
            Console.WriteLine("Team "   teamObj.teamName   " created");

            str = Console.ReadLine();
            count = Convert.ToInt32(str);
            Console.WriteLine("Current number of players in team "   teamObj, teamName   " is "   teamObj.noOfPlayers);
            teamObj.AddPlayer(count);
            Console.WriteLine("New number of players in team "   teamObj.teamName   " is "   teamObj.onOfPlayers);

            str = Console.ReadLine();
            count = Convert.ToInt32(str);
            Console.WriteLine("Current number of players in team "   teamObj.teamName   " is "   teamObj.onOfPlayers);
            var res = teamObj.RemovePlayer(count);
            if(res)
            {
                Console.WriteLine("New number of players in team "   teamObj.teamName   " is "   teamObj.onOfPlayers);
            } else
            {
                Console.WriteLine("Number of players in team "   teamObj.teamName   " remains same");
            }

            str = Console.ReadLine();
            teamObj.ChangeTeamName(str);
            Console.WriteLine("Team name of team "   initialName   " changed to "   teamObj.teamName);
        }
    }
}

CodePudding user response:

If I understand you correctly, and you don't want the ChangeTeamName method on the Team class then you'll need to make the teamName field protected so that the derived SubTeam class can access and modify it.

You have not added an access modifier to the teamName field so it has default access of private meaning that it can only be read or changed from inside the class it's defined in, the Team class.

protected means it can be accessed from this class itself and and derived (sub) classes.

internal means it can be accessed by any class in the same assembly (dll or project).

public means it can be accessed from anywhere.

I recommend using a property instead of a class for protected access.

public class Team
{
    protected string TeamName { get; set; }
    int noOfPlayers;

    public Team(string teamName, int noOfPlayers)
    {
        this.TeamName = teamName;
        this.noOfPlayers = noOfPlayers;
    }

    etc.
}
class Subteam : Team
{
    public Subteam(string teamName, int noOfPlayers) : base(teamName, noOfPlayers)
    {           
    }

    public void ChangeTeamName(string name)
    {
        this.TeamName = name;
    }
}

CodePudding user response:

It's likely that you are running into this problem because the default protection level when none is specified is private and therefore the derived class cannot access the base's variable. You can change this to protected so that derived classes can use the variable or alternatively (though perhaps not recommended) is to make it public altogether.

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        (new C() {Index = 1}).Print();
    }
}

public class B
{
    public int Index {get; set;}
}

public class C : B {
    public void Print(){
        Console.WriteLine(this.Index);
    }
}
  • Related