Difference between revisions of "2021 - Private vs Protected"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "=What is Private= A variable or method can be declared 'private', this means that it will only be available within objects of the class it is declared in. It won't even be ava...")
 
(Example in the code)
 
Line 31: Line 31:
 
         public HexGrid(int n) : base(n)
 
         public HexGrid(int n) : base(n)
 
         {
 
         {
            size = n;
+
 
            SetUpTiles();
 
            SetUpNeighbours();
 
            player1Turn = true;
 
 
         }
 
         }
 
     }
 
     }

Latest revision as of 10:50, 24 September 2020

What is Private

A variable or method can be declared 'private', this means that it will only be available within objects of the class it is declared in. It won't even be available in subclasses. The default is to make a variable private, so the code below shows both 'int size;' and 'bool player1Turn;' are both 'private'.

What is Protected

Protected relatively the same as 'private', however a 'protected' variable or method will be available within any subclass.

Example in the code

class HexGrid
    {
        protected List<Tile> tiles = new List<Tile>();
        protected List<Piece> pieces = new List<Piece>();
        int size;
        bool player1Turn;

        public HexGrid(int n)
        {
            size = n;
            SetUpTiles();
            SetUpNeighbours();
            player1Turn = true;
        }
     }

So if we made a subclass of 'HexGrid' for example 'BigHexGrid':

class BigHexGrid : HexGrid
    {
        public HexGrid(int n) : base(n)
        {

        }
     }

'tiles' and 'pieces' will be available in the subclass (via inheritance) but 'size' and 'player1Turn' won't be available.