Class structure

This is a general tutorial about the class structure of programming languages.

The class is basically an object that allows public methods (accessed outside that class object) and private methods (the internal class logic) and protected with is the same as private apart from an inherited class can access the protected objects. Basically the 3 main types

Public : Access from outside the class, and internal of course, with inherited/friends etc.
Protected : Access from inherited/friends of the class, but not called from the class object.
Private : Access from only the class and friends of the class.

For example within C# coding …

class example1
       private int value1;
       private int value2;
       protected int value3;
       public int addtwo(int a, int b)
              value1 = a;
              value2 = b;
              value3 = (a+b);              // setup the local variables
              return value3;
       public int returnValue()
              return value1;
class example2 : example1
       public int returnValue2()
              return value2;       // will error due to value2 is private in the inherited class
              //return 0;              // to be able to compile
       public int returnValue3()
              return value3;       // fine since a protected part of the inherited class
class examples 
       static public void Main()
              example1 ex = new example1();
              example2 ex2 = new example2();
              // add the two numbers and set the local internal variables
              System.Console.WriteLine("Two numbers 3 + 4 = " + ex.addtwo(3,4));
              // output the value1 from the internal example1 class
              System.Console.WriteLine("Value1 = " + ex.returnValue());
              // Just for demo'ing, since the example2 is not linked to example1, just inherites it.
              System.Console.WriteLine(ex2.returnValue2());       // will not compile the class above.

save as classexample.cs. The output will be

Two numbers 3 + 4 = 7
Value1 = 3

The two zero’s are because class example2 only inherits the example class and not does not link to it. I have added the line within the example2 returnValue2 method to be able to compile the source code otherwise you will get the error similar to

classexample.cs(25,10): error CS0122: example1.value2 is inaccessible due to its protection level

Leave a Reply

Your email address will not be published. Required fields are marked *