Inheritance and Polymorphism
Protected Members
A protected member is visible inside the class and its derived classes.
Protected Members
ProtectedMembers.cs
using System;
class Account
{
protected int balance;
public Account(int openingBalance)
{
balance = openingBalance;
}
}
class SavingsAccount : Account
{
public SavingsAccount(int openingBalance) : base(openingBalance)
{
}
public void AddInterest(int amount)
{
balance += amount;
}
public int Balance
{
get { return balance; }
}
}
class Program
{
static void Main()
{
int interest = ;
SavingsAccount account = new SavingsAccount(20);
account.AddInterest(interest);
Console.WriteLine($"interest={interest}");
Console.WriteLine($"balance={account.Balance}");
}
}
using System;
class Account
{
protected int balance;
public Account(int openingBalance)
{
balance = openingBalance;
}
}
class SavingsAccount : Account
{
public SavingsAccount(int openingBalance) : base(openingBalance)
{
}
public void AddInterest(int amount)
{
balance += amount;
}
public int Balance
{
get { return balance; }
}
}
class Program
{
static void Main()
{
int interest = ;
SavingsAccount account = new SavingsAccount(20);
account.AddInterest(interest);
Console.WriteLine($"interest={interest}");
Console.WriteLine($"balance={account.Balance}");
}
}
using System;
class Account
{
protected int balance;
public Account(int openingBalance)
{
balance = openingBalance;
}
}
class SavingsAccount : Account
{
public SavingsAccount(int openingBalance) : base(openingBalance)
{
}
public void AddInterest(int amount)
{
balance += amount;
}
public int Balance
{
get { return balance; }
}
}
class Program
{
static void Main()
{
int interest = ;
SavingsAccount account = new SavingsAccount(20);
account.AddInterest(interest);
Console.WriteLine($"interest={interest}");
Console.WriteLine($"balance={account.Balance}");
}
}
protected
Protected members share state with derived classes without making it public.