0% found this document useful (0 votes)
64 views25 pages

Code Samples

Inheritance allows classes to inherit functionality from base classes and override functionality as needed. The example shows a base Animal class with a display method, and a Dog class that inherits from Animal and adds a getName method while still having access to display. Abstraction hides internal details and shows only functionality through abstract classes and methods. The example shows an abstract Animal class with an abstract animalSound method, and a Pig class that inherits and provides the implementation. Polymorphism allows different classes to provide unique implementations of the same method. The example shows different animal classes all providing their own version of the animalSound method.

Uploaded by

Kasun Jayamina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views25 pages

Code Samples

Inheritance allows classes to inherit functionality from base classes and override functionality as needed. The example shows a base Animal class with a display method, and a Dog class that inherits from Animal and adds a getName method while still having access to display. Abstraction hides internal details and shows only functionality through abstract classes and methods. The example shows an abstract Animal class with an abstract animalSound method, and a Pig class that inherits and provides the implementation. Polymorphism allows different classes to provide unique implementations of the same method. The example shows different animal classes all providing their own version of the animalSound method.

Uploaded by

Kasun Jayamina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Object Oriented Programming

Inheritance

Inheritance is a feature of object-oriented programming languages that allows you


to define a base class that provides specific functionality (data and behavior) and to
define derived classes that either inherit or override that functionality.

using System;
namespace Inheritance {

// base class
class Animal {

public string name;

public void display() {


Console.WriteLine("I am an animal");
}
}

// derived class of Animal


class Dog : Animal {

public void getName() {


Console.WriteLine("My name is " + name);
}
}
class Program {
static void Main(string[] args) {

// object of derived class


Dog labrador = new Dog();

// access field and method of base class


labrador.name = "Rohu";
labrador.display();

// access method from own class


labrador.getName();

Console.ReadLine();
}
}
}

Output
I am an animal
My name is Rohu
Abstraction

Abstraction in C# is the process to hide the internal details and show only the
functionality. The abstract modifier indicates the incomplete implementation. The
keyword abstract is used before the class or method to declare the class or method
as abstract.

// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}

// Derived class (inherit from Animal)


class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}

Output
The pig says: wee wee
Zzz

Sub Topics

C# Interface

Interface in C# is a blueprint of a class. It is like abstract class because all the


methods which are declared inside the interface are abstract methods. It cannot
have method body and cannot be instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is
used to achieve fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which
implements the interface, must provide the implementation of all the methods
declared inside the interface.
using System;
public interface Drawable
{
void draw();
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
}
}

Output
drawing ractangle...
drawing circle...
Polymorphism

Polymorphism, in C#, is the ability of objects of different types to provide a unique


interface for different implementations of methods. It is usually used in the context
of late binding, where the behavior of an object to respond to a call to its method
members is determined based on object type at run time.

class Animal // Base class (parent)


{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
Output
The animal makes a sound
The animal makes a sound
The animal makes a sound

Sub Topics

Method Overloading

Method overloading allows programmers to use multiple methods with the same
name. The methods are differentiated with their number and type of method
arguments. Method overloading is an example of the polymorphism feature of an
object-oriented programming language.

using System;

namespace MethodOverload {

class Program {

// method with one parameter


void display(int a) {
Console.WriteLine("Arguments: " + a);
}

// method with two parameters


void display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b);
}
static void Main(string[] args) {

Program p1 = new Program();


p1.display(100);
p1.display(100, 200);
Console.ReadLine();
}
}
}

Output
Arguments: 100
Arguments: 100 and 200
Method Overriding

If derived class defines same method as defined in its base class, it is known as
method overriding in C#. It is used to achieve runtime polymorphism. It enables
you to provide specific implementation of the method which is already provided by
its base class.
To perform method overriding in C#, you need to use virtual keyword with base
class method and override keyword with derived class method.

using System;
public class Animal{
public virtual void eat(){
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding
{
public static void Main()
{
Dog d = new Dog();
d.eat();
}
}

Output
Eating bread...

C# Base

In C#, base keyword is used to access fields, constructors and methods of base
class.
You can use base keyword within instance method, constructor or instance
property accessor only. You can't use it inside the static method.

using System;
public class Animal{
public virtual void eat(){
Console.WriteLine("eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
base.eat();
Console.WriteLine("eating bread...");
}

}
public class TestBase
{
public static void Main()
{
Dog d = new Dog();
d.eat();
}
}

Output
eating...
eating bread...

C# Sealed Class

C# sealed keyword applies restrictions on the class and method. If you create a
sealed class, it cannot be derived. If you create a sealed method, it cannot be
overridden.
using System;
sealed public class Animal{
public void eat() { Console.WriteLine("eating..."); }
}
public class Dog: Animal
{
public void bark() { Console.WriteLine("barking..."); }
}
public class TestSealed
{
public static void Main()
{
Dog d = new Dog();
d.eat();
d.bark();

}
}

Output
Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'
Encapsulation

Encapsulation, in the context of C#, refers to an object's ability to hide data and
behavior that are not necessary to its user. Encapsulation enables a group of
properties, methods and other members to be considered a single unit or object.

// C# program to illustrate encapsulation


using System;

public class DemoEncap {

// private variables declared


// these can only be accessed by
// public methods of class
private String studentName;
private int studentAge;

// using accessors to get and


// set the value of studentName
public String Name
{

get
{
return studentName;
}
set
{
studentName = value;
}
}

// using accessors to get and


// set the value of studentAge
public int Age
{

get
{
return studentAge;
}
set
{
studentAge = value;
}
}
}

// Driver Class
class GFG {
// Main Method
static public void Main()
{
// creating object
DemoEncap obj = new DemoEncap();

// calls set accessor of the property Name,


// and pass "Ankita" as value of the
// standard field 'value'
obj.Name = "Ankita";

// calls set accessor of the property Age,


// and pass "21" as value of the
// standard field 'value'
obj.Age = 21;

// Displaying values of the variables


Console.WriteLine("Name: " + obj.Name);
Console.WriteLine("Age: " + obj.Age);
}
}

Output
Name: Ankita
Age: 21
Constructor in C#

A constructor is a special method that is used to initialize objects. The advantage of


a constructor, is that it is called when an object of a class is created.

// Create a Car class


class Car
{
public string model; // Create a field

// Create a class constructor for the Car class


public Car()
{
model = "Mustang"; // Set the initial value for model
}

static void Main(string[] args)


{
Car Ford = new Car(); // Create an object of the Car Class (this will call the
constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}

// Outputs "Mustang"
Data Structures

Queue

A Queue is used to represent a first-in, first out(FIFO) collection of objects. It is


used when you need first-in, first-out access of items. It is the non-generic type of
collection which is defined in System. Collections namespace. It is used to create a
dynamic collection which grows, according to the need of your program. In Queue,
you can store elements of the same type and of the different types. Generally, a
queue is helpful when you access that information in the same way in which they
stored in the collection and it is temporary storage to store data.

// C# program to illustrate queue


using System;
using System.Collections;

public class GFG {


static public void Main()
{

// Create a queue
// Using Queue class
Queue my_queue = new Queue();

// Adding elements in Queue


// Using Enqueue() method
my_queue.Enqueue("GFG");
my_queue.Enqueue(1);
my_queue.Enqueue(100);
my_queue.Enqueue(null);
my_queue.Enqueue(2.4);
my_queue.Enqueue("Geeks123");

// Accessing the elements


// of my_queue Queue
// Using foreach loop
foreach(var ele in my_queue)
{
Console.WriteLine(ele);
}
}
}

Output
GFG
1
100

2.4
Geeks123
Stack

A Stack represents a last-in, first-out collection of objects. It is used when you


need last-in, first-out access to items. It is both a generic and non-generic type of
collection. The generic stack is defined in System.Collections.Generic namespace
whereas non-generic stack is defined under System.Collections namespace, here
we will discuss non-generic type stack. A stack is used to create a dynamic
collection that grows, according to the need of your program. In a stack, you can
store elements of the same type or different types.

// C# program to illustrate how to


// create a stack
using System;
using System.Collections;

class GFG {

// Main Method
static public void Main()
{

// Create a stack
// Using Stack class
Stack my_stack = new Stack();

// Adding elements in the Stack


// Using Push method
my_stack.Push("Geeks");
my_stack.Push("geeksforgeeks");
my_stack.Push('G');
my_stack.Push(null);
my_stack.Push(1234);
my_stack.Push(490.98);

// Accessing the elements


// of my_stack Stack
// Using foreach loop
foreach(var elem in my_stack)
{
Console.WriteLine(elem);
}
}
}

Output
490.98
1234

G
geeksforgeeks
Geeks
Star Patterns in C#

Example 01
*
**
***
****
*****
******

using System.IO;
using System;
class Program {
static void Main() {
for (int i = 1; i <= 6; ++i) {
for (int j = 1; j <= i; ++j) {
Console.Write("*");
}
Console.WriteLine();
}
}
}
Example 02

******
*****
****
***
**
*

using System.IO;
using System;
class Program {
static void Main() {
for (int i = 6; i >= 1; --i) {
for (int j = 1; j >= i; ++j) {
Console.Write("*");
}
Console.WriteLine();
}
}
}
Example 03

*
***
*****
*******
*********
***********
*********
*******
*****
***
*

using System.IO;
using System;
class Demo {
static void Main() {
int a = 1, spaces, k = 6, i = 0, j = 0;
spaces = k - 1;
for(i=1; i<k*2; i++) {
for(j=1; j<=spaces; j++) {
Console.Write(" ");
}
for(j=1; j<a*2; j++) {
Console.Write("*");
}
Console.WriteLine("");
if(i < k) {
spaces--;
a++;
} else {
spaces++;
a--;
}
}
}
}

You might also like