Classes and Objects in C#
C# is an Object-Oriented Programming Language. Class is Template used to define the properties and Actions performed by the Object. Object is an Instance of a class. Object are used to access the public members of the class.
Introduction
C# is a Object-Oriented Programming Language. Class is Template used to define the properties and Actions performed by the Object. Object is an Instance of a class.Class
1. It is Template used to define the Properties and Actions of an Object.
2. Properties are represented by using variables.
3. Actions are implemented by using Methods(Functions).
4. In C# all the programming statements are placed inside the class Definition.
5. Keyword "class" is used in the class definition.
6. By Default in C# all the Class Members are private
Syntax
class classname {
// Variable Declarations
// Method definitions
} Object
1. It is an Instance of a class.
2. When the Object is created the variables defined in the class will be binded to the Object.
3. Initialized Object is used to access the public variables and Methods in the class.
Syntax
classname objectName = new constructorname();
Example
Define a class called Bike with two variables model and brand. Define a Methods to Assign the value and also to display the values.
// Example: Classes and Objects
class Bike {
// variable declaration
String model;
String brand;
// Method to assign the bike details(Without parameter)
public void assignBikeDetails() {
model = "CT-100";
brand = "Bajaj";
}
// Method to assign the bike details (With parameter)
public void assgnBikeDetails1(String m, String b){
model = m;
brand = b;
}
// Method to display the Bike details
public void showBikeDetails() {
System.out.println("Model = " + model);
System.out.println("Brand = " + brand);
}
} // End of the class definition
// Implementation class
class ClassDemo {
public static void Main() {
// Object Creation
Bike objBike;
// Object Initialization
objBike = new Bike();
// Invoking the Method without parameter
objBike.assgnBikeDetails();
objBike.showBikeDetails();
// Object Creation and Initialization
Bike objBike1 = new Bike();
// Invoking the Method with parameter
objBike1.assgnBikeDetails1("Splendor", "Hero-Honda");
objBike1.showBikeDetails();
}
}
Note:
1. Variable declared inside the class is called as an Instance variable.
2. new Operator dynamically allocates the memory for the object.