ClassesAndObjects.md - brainchildservices/curriculum GitHub Wiki

Slide 1

C# Classes And Objects

image

A class is a template for objects, and an object is an instance of a class.

Slide 2

Eg: An animal is a class. The different types of animals like cat, dog, etc are the objects of the class animal.

image

Slide 3

A class declaration consists of a class header and body. The class header includes attributes, modifiers, and the class keyword. The class body encapsulates the members of the class, which are the data members and member functions. These class members can be fields, properties, or methods.

The syntax of a class declaration is as follows:
Accessibility Modifiers class NameofClass
{
body of class containing data members and member functions
}

Accessibility can be public, private, etc
Modifiers can be static, abstract, sealed, etc


Slide 4

Eg1:

  public static class Animal  
  {  
  body of the class  
  }  

Eg2:

  public class Car  
  {  
  body of the class  
  }  

Slide 5

A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object.

An object can be created using the new keyword. This process is called instantiation or object creation.

Syntax

ClassName objectName = new ClassName();


Eg:

  Car Audi=new Car();

Slide 6

An object cannot be created when the class is static. Members of the static classes are accessed using the classname.

Q. What do you have to do if you are asked to create an instance of a class or object of a class or instantiate the class?

Ans: We need to create an object of the class using the new keyword if we are asked to create instance of a class or object of a class or instantiate the class

  Classname objectName=new ClassName();

Slide 7

Exercise:
Q1. Create a public class Furniture. In Main method create an object chair of class Furniture.
Q2. Create a public class Vehicle. In Main method create an object bike of class Vehicle.
Q3. Create a public class Grocery. In Main method create an object vegetable of class Grocery.