0% found this document useful (0 votes)
32 views

07 Inheritance and Polymorphism

The document discusses inheritance and polymorphism in object-oriented programming. It defines inheritance as allowing a child class to reuse or inherit the behavior of a parent class. Single inheritance in C# allows a subclass to inherit from only one superclass. Protected members of a base class can be accessed by derived classes, while private members cannot. Derived classes can call or invoke constructors of the base class using the base keyword to initialize inherited data members.

Uploaded by

erikalast.acad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

07 Inheritance and Polymorphism

The document discusses inheritance and polymorphism in object-oriented programming. It defines inheritance as allowing a child class to reuse or inherit the behavior of a parent class. Single inheritance in C# allows a subclass to inherit from only one superclass. Protected members of a base class can be accessed by derived classes, while private members cannot. Derived classes can call or invoke constructors of the base class using the base keyword to initialize inherited data members.

Uploaded by

erikalast.acad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

IT1907

Inheritance and Polymorphism


Inheritance
Inheritance is one of the principles of object-oriented programming that allows the defining of a child class that reuses or
inherits the behavior of a parent class (or existing class). The inheriting class is called a derived class or subclass. The existing
class whose members are being inherited is called base class or superclass. The C# programming language only supports single
inheritance, where a subclass can only inherit from a single superclass. The figure below illustrates an example of inheritance.
In Figure 1, Student and Teacher are derived classes of the
base class Person. These derived classes can reuse or
inherit the behavior (methods) of the superclass Person,
such as setName() and Walk(). The Student and Teacher
classes can use the method Walk() without recreating their
own Walk() method. These derived classes can have their
own methods or properties.
Because inheritance is transitive, the members of the class
Person is available to the upcoming derived classes of the
Student or Teacher classes.

Figure 1. Inheri ta nce us i ng UML cl a s s di a gra ms

The following statement is the general syntax for inheriting a class in C#:
access_modifier class DerivedClass : BaseClass {
//class members here...
}
The colon (:) symbol indicates that the class DerivedClass inherits the members of the class BaseClass. The derived classes do
not inherit the base class' constructors, but these derived classes can invoke (or call) the constructors of the base class. The
following programs show how to declare inheritance:
Example 1. Student cl a s s i nheri ts from Person cl a s s
BASE CLASS DERIVED CLASS
using System; using System;
namespace PersonNamespace { namespace PersonNamespace {
public class Person { public class Student : Person {
private string full_name; private string program;
public void setName() { public void EnrollProgram() {
this.full_name = "no name"; this.setName();
} this.program = "not enrolled";
}
public void Walk() {
Console.WriteLine("Walking..."); public void ComputeGrade() {
} Console.WriteLine("Computing grade...");
} }
} }
}
In the given example, the derived class Student inherits from the base class Person, including the field name and behavior. The
Student class can now have access to the members of the Person class, such as the method setName(), and can be invoked
using the this keyword since the methods of the derived class inherited the base class. The Person and Student classes are
both members of the namespace PersonNamespace. This is used to help in organizing the classes.
A derived class can inherit the private members of a base class, but these are not accessible. In Example 1, the instance variable
full_name of Person class is private. When the class Student class inherits the members of Person class, it will inherit the
field full_name, but it cannot access this variable. For example, when the statement this.full_name = "no name"; is
declared in the class Student, it will cause an error since the field full_name is private. When an instance variable of a base
class is declared as private, the derived class can only access that variable through methods or by using properties. The variable
07 Handout 1 *Property of STI
[email protected] Page 1 of 7
IT1907
full_name in Example 1 can only be accessed or initialized using the method setName(). Declaring the members of a superclass
as private prevents its subclasses from modifying the members of the superclass.
Protected Members of a Class
Unlike private, the protected members of a base class
are inherited and are accessible by their derivedclasses.
The keyword protected is used to declare a protected
member. Members of a superclass are declared
protected if you want its subclasses to access its
members. Figure 2 illustrates a UML diagram with
protected members. Example 2 shows the example
programs of how to declare use protected members in
inheritance.

Figure 2. Inheri ta nce us i ng UML cl a s s di a gra ms wi th protected members


Example 2. Teacher cl a s s i nheri ts from Person cl a s s a nd decl a res protected members
BASE CLASS DERIVED CLASS
namespace PersonNamespace { using System;
public class Person {
namespace PersonNamespace {
protected string full_name;
public class Teacher : Person {
private int age;
private string department;
public void setInfo() {
public Teacher(string name, string dept) {
this.full_name = "no name";
this.full_name = name;
this.age = 0;
this.department = dept;
}
}
}
public void TeachClass() {
}
Console.WriteLine("Teaching class...");
}
public double setSalary() {
return 0;
}
}
}
In Example 2, the instance variable full_name of the base class Person is declared protected and can be accessed by its derived
classes. The derived class Teacher inherits the members of the Person class. In the constructor Teacher (string name,
string dept), the this.full_name is accessed and initialized by its derived class from the base class.
Calling Base Class Constructors
When a derived class inherits from a base class, it does not inherit the constructors of the base class to prevent problems in
initializing fields of an object, but derived classes can invoke the constructors of the base class which can help in initializingthe
fields of an instance of the class. Calling the constructor of a base class from the constructor in the derived class is used to
initialize the inherited data members of a derived class from the base class.
In C#, the base keyword is used to specify which constructor from the base class should be invoked when creating instances of
the derived class. The following statements show how to use base keyword when calling a base class constructor from the
derived class constructor.
access_modifier class DerivedClass : BaseClass {
public DerivedClassConstructor(parameter_list) : base(arguments of base class constructor) {
//statement(s)
}
}

07 Handout 1 *Property of STI


[email protected] Page 2 of 7
IT1907
Figure 3 illustrates two (2) UML diagrams with constructors. Example 3 below
demonstrates how to invoke a base class constructor to initialize the instance
of the derived class.

Figure 3. UML cl a s s di a gra ms wi th cons tructors


Example 3. Student cl a s s i nheri ts from Person cl a s s us i ng the base keyword
BASE CLASS
using System;
namespace PersonNamespace {
public class Person {
private string full_name;
private int age;
public Person(string name, int age) {
this.full_name = name;
this.age = age;
}
public void displayInfo() {
Console.WriteLine("Name: " + this.full_name);
Console.WriteLine("Age: " + this.age);
}
}
}
DERIVED CLASS
using System;
namespace PersonNamespace {
public class Student : Person {
private long student_id;
private string student_program;
public Student(string name, int age, long id, string program) : base(name, age) {
this.student_id = id;
this.student_program = program;
}
public void displayStudentInfo() {
base.displayInfo();
Console.WriteLine("Student ID: " + this.student_id);
Console.WriteLine("Program: " + this.student_program);
}
}
}
CREATING AN INSTANCE OF THE STUDENT CLASS USING THE DEFINED CONSTRUCTOR
using PersonNamespace;
public class Program {
static void Main(string[] args) {
Student s1 = new Student("Jack Paul", 18, 20191001, "BSCS");
s1.displayStudentInfo();
}
}

07 Handout 1 *Property of STI


[email protected] Page 3 of 7
IT1907

OUTPUT
Name: Jack Paul
Age: 18
Student ID: 20191001
Program: BSCS
In the base class Person of Example 3, the constructor Person(string name, int age) is defined and initializes its instance
variables full_name and age. In the derived class, the constructor Student(string name, int age, long id, string
program) with base(name, age) is used for calling the base class constructor Person(string name, int age) to initialize
the inherited instance variables full_name and age of class Student with the values from the parameter of its constructor.
Then, the constructor of Student will initialize the instance variables student_id and student_program. The base keyword
can also be used to call a method from the base class. For example, there is base.displayInfo();.
When creating an instance of the derived class Student using the defined constructor, the required arguments of the
constructor must be defined. In the example, the parameterized constructor of Student creates a new instance using the
statement Student s1 = new Student("Jack Paul", 18, 20191001, "BSCS");, where the defined arguments match the
required parameters of the constructor.
Method Overriding
A derived class inherits the methods of its base class. Declaring a
method in a derived class with the same name as the method from
its base class is called method overriding. Method overriding is
redefining the functionality of an existing method. This is used for
defining a specific behavior to the overriding method of a derived
class that is different from the existing method from its base class.
For example, the derived class CheckingAccount in Figure 4
overrides the method withdraw from the base class BankAccount.
The method withdraw (overridden method) of BankAccount takes the
amount to withdraw then subtracts it from the current balance.
Consequently, the method withdraw (overriding method)
of CheckingAccount has a different behavior. This method adds
a withdrawal fee on the amount to withdraw before subtracting
it from the current balance.
Figure 4. Inheritance with overridden and overriding method The override method should have the same method signature
(access modifier, return type, method name, and parameter list) as
the overridden method.
In C#, the overridden method from the base class should be declared as virtual. If the class is abstract, the overridden
method should be declared abstract or virtual. The virtual modifier specifies that a derived class can override the method
in the base class. When overriding a virtual method from the base class, the override modifier is required to modify the
abstract or virtual implementation of the inherited method and must have the same method signature as the overridden
method (virtual method). Only an abstract and virtual method can be overridden in C#. The following programs demonstrate
how to declare a virtual method and create an overriding method, including how to declare and access properties.
Example 4. CheckingAccount cl a s s i nheri ts from BankAccount cl a s s with a n overri de method a nd Program cl a s s with Main method
BASE CLASS
namespace BankAccountNamespace {
public class BankAccount {
private long account_number;
private double current_balance;
private double withdrawal_amount;
public BankAccount(long account, double balance) {
this.account_number = account;
this.current_balance = balance;

07 Handout 1 *Property of STI


[email protected] Page 4 of 7
IT1907
}
public virtual void withdraw(double amount) {
//subtract the amount to withdraw from the current balance
this.current_balance = this.current_balance - amount;
}
public long cardNumber {
get {
return this.account_number;
}
set {
this.account_number = value;
}
}
public double accountBalance {
get {
return this.current_balance;
}
set {
this.current_balance = value;
}
}
public double withdrawnAmount {
get {
return this.withdrawal_amount;
}
set {
this.withdrawal_amount = value;
}
}
}
}
DERIVED CLASS
namespace BankAccountNamespace {
public class CheckingAccount : BankAccount {
private double withdrawal_fee = 12.25;
public CheckingAccount(long account, double balance) : base(account, balance) {
//no instance variable to initialize
}
public override void withdraw(double amount) {
/* add fee to the amount and use the base keyword to invoke the overridden method from
the base class. The withdrawnAmount property is used to set the withdrawn amount.*/
this.withdrawnAmount = amount;
amount = amount + this.withdrawal_fee;
base.withdraw(amount);
}
public double transactionFee {
get {
return this.withdrawal_fee;
}
set {
this.withdrawal_fee = value;
}
}
}
}
07 Handout 1 *Property of STI
[email protected] Page 5 of 7
IT1907

CREATING AN INSTANCE OF THE STUDENT CLASS USING THE DEFINED CONSTRUCTOR


using System;
using BankAccountNamespace;
public class Program {
static void Main(string[] args) {
CheckingAccount clientAccount = new CheckingAccount(1234567890, 30102.84);
clientAccount.withdraw(3500); //invokes the override method from the derived class
//print the receipt by accessing the get and set properties of the clientAccount object
Console.WriteLine("<------Transaction Receipt------>");
Console.WriteLine("CARD NUMBER: " + clientAccount.cardNumber);
Console.WriteLine("---------------------------------");
Console.WriteLine("WITHDRAWAL:\t\t" + clientAccount.withdrawnAmount);
Console.WriteLine("TRANSACTION FEE:\t" + clientAccount.transactionFee);
double total = (clientAccount.withdrawnAmount + clientAccount.transactionFee);
Console.WriteLine("TOTAL CHARGED:\t\t" + total);
Console.WriteLine("---------------------------------");
Console.WriteLine("AVAILABLE BALANCE:\t" + clientAccount.accountBalance);
}
}
OUTPUT
<------Transaction Receipt------>
CARD NUMBER: 1234567890
---------------------------------
WITHDRAWAL: 3512.25
TRANSACTION FEE: 12.25
TOTAL CHARGED: 3524.5
---------------------------------
AVAILABLE BALANCE: 26590.59
In the base class BankAccount of Example 4, the withdraw method is declared as virtual, which is inherited by the derived
class CheckingAccount. The derived class overrides the inherited method using the override modifier to define a different
behavior of the override method. In the override withdraw method of the derived class, the base keyword invokes the
overridden method from the base class to execute the statements, which subtract the amount to withdraw from the current
balance.
Abstract Classes
An abstract class is a base class that cannot be instantiated to create an
object. The purpose of an abstract class is to provide an outline and class
members that must be implemented to its derived classes. The abstract
keyword is used to declare an abstract class and is placed before the class
name. The following statements demonstrate how to declare an abstract
class using the abstract keyword in C#:
public abstract class BankAccount {
//class members
}
An abstract class may contain abstract methods that must be declared as a
member of the abstract class. An abstract method is a method header with
an abstract modifier that has no implementation or method body, for its
implementation is provided by overriding it on derived class. The following
statement shows how to declare an abstract method in C#:
public abstract void deposit(double amount);
An abstract method must be declared within the abstract class and must have
a semicolon (;) after parentheses (()). When you do not want the base
Figure 5. Abs tra ct cl a s s a nd a bs tra ct method
class to be instantiated, declare it as an abstract class.

07 Handout 1 *Property of STI


[email protected] Page 6 of 7
IT1907
The following programs demonstrate how to declare an abstract class and abstract methods and override abstract methods.
Example 5. SavingsAccount cl a s s i nheri ts from the a bs tra ct cl a s s BankAccount wi th a n a bs tra ct method
BASE CLASS
namespace BankAccountNamespace {
public abstract class BankAccount {
protected long account_number;
protected double current_balance;
public double getBalance() {
return this.current_balance;
}
public abstract void deposit(double amount);
}
}
DERIVED CLASS
namespace BankAccountNamespace {
public class SavingsAccount : BankAccount {
private double interestRate = 0.0125; //this is 1.25%
public override void deposit(double amount) {
this.current_balance += amount;
}
public void addInterest() {
this.current_balance += (this.current_balance * interestRate ) / 100;
}
}
}

In the example above, the base class BankAccount is declared as an abstract, which contains the abstract method deposit. The
derived class SavingsAccount is required to implement deposit and provide its method body and behavior. The derived class
may declare its own instances and methods, such as addInterest.
Polymorphism
Polymorphism, which means “multiple forms,” is one of the fundamental concepts of object-oriented programming.Itenables
classes to provide multiple methods with the same name but with different implementations or behavior. Polymorphism has
two (2) different forms: compile time and runtime polymorphisms.
• Compile time polymorphism – Also known as “static polymorphism,” this polymorphism is implemented using method
overloading. In method overloading, a method is executed depending on the number and type of parameters passed to it.
When a program is compiled, the compiler binds the appropriate method to the object based on the method’s arguments.
This process is called early binding.
• Runtime polymorphism – This polymorphism is a process in which the compiler determines which method to call during
runtime. This process is also called dynamic polymorphism or late binding. This is achieved using method overriding.

REFERENCES:
Deitel, P. and Deitel, H. (2015). Visual C# 2012 how to program, (5th Ed.). USA: Pearson Education, Inc.
Gaddis, T. (2016). Starting out with visual C# (4th Ed.). USA: Pearson Education, Inc.
Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR.

07 Handout 1 *Property of STI


[email protected] Page 7 of 7

You might also like