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 etc.
Protected : Access from inherited of the class, but not called from the class object.
Private : Access from only the class and friends of the class.

This is 3 Java source code to demonstrate

class classexample
{
       private       int value1;
       private       int value2;
       protected int value3;
 
       public int addtwo(int a, int b)
       {
              value1 = a;
              value2 = b;
              value3 = (a + b);
              return value3;
       }
 
       public int returnValue1()
       {
              return value1;
       }
}

save as classexample.java

class classexample2 extends classexample
{
       public int returnValue2()
       {
              //return value2;       // will error due to value2 is private in the inherited class
              return 0;              // to be able to compi
       }
 
       public int returnValue3()
       {
              return value3;       // fine since a protected part of the inherited class
       }
}

save as classexample2.java

class classex
{
       static public void main(String args[])
       {
              classexample example1 = new classexample();
              classexample2 example2 = new classexample2();
              System.out.println("Class 1, adding two numbers and setting the internal numbers");
              System.out.println(example1.addtwo(3,4));
              // of course will return 0, because example2 is not connected to example1 class, 
              // it just extends the definition of that class.
              System.out.println(example2.returnValue3());
       }       
}

save as classex.java

And to compile the tutorial just need to java classex because java will compile the other classes as well (and creates the class files). Once compiled the output will be

Class 1, adding two numbers and setting the internal numbers
7
0

Leave a Reply

Your email address will not be published.