C#

private VS public VS protected VS abstract VS virtual

Naranjito 2023. 2. 21. 19:29
  • private

Accessible only within the same class. Default.

 

  • public

Accessible from all the class.

 

  • protected

Accessible only from the class inherited.

 

  • virtual

It allows to be modified and overridden in a derived class(inherited, children).

 

  • abstract

It does not have a body in parents class, body must to be completed in inherited class(children).

If the class has abstract method, class needs to use abstract class too.

 

Script1.(parents class)

1. The class has protected variables.

2. The class has protected virtual method.

3. The class has abstract protected method.

4. The class needs to use abstract class too.

# 4
abstract public class part: MonoBehaviour //if there is an abstract method, it needs to use abstract class too.
{

# 1
    protected string humanName; 
    protected int humanAge; 

# 2
    protected virtual void Info() //create vuitual function in other to be modified from other class
    {
         print("I am a human");
    }

# 3
    abstract protected void Name(); //It does not have a body in parents class
}

 

Script2.(children class)

1. Inherits Script1 class.

2. Use 'override' when you want to modify the function from parents class.

3. Call it(2) using with 'base'.

4. You cannot forget to embody the function from parents class if there is abstract method. 

5. Use it(4).

# 1
public class part2 : part //inherits part class
{

    string schoolName;

    void Start()
    {
        schoolName="julia school";
        humanName="julia";
        humanAge=13;

        Info(); //call the function from other class in other script
    }

# 2
    protected override void Info() //Re-define the function from other class in other script
    {
    
# 3
        base.Info(); //Base indicates parents class
        print("I am a student.");
    }

# 4, 5
    protected override void Name()
    {
        print(humanName);
    }
}