Addition 2
Addition 2
Classes:
In C#, a class is a blueprint or template for creating objects that share similar
characteristics and behavior. A class contains fields (also known as data members
or attributes) and methods that define the object's data and behavior,
respectively.
Fields are variables that store data within an object, and methods are functions
that can manipulate the object's data or perform some other action. Together, the
fields and methods define the object's properties and behavior.
Here is an example of a simple class definition in C#:
public class Person
{
// Fields (variables and data containers)
public string name;
public int age;
2.Access Modifiers public and private are used to control the visibility
of classes and their members (such as fields and methods) outside of the class
itself.
A public class is one that can be accessed from any other code within the same
project or assembly. This means that any other code can create an instance of the
class and access its public members (fields and methods). In other words, a public
class has no restrictions on its accessibility.
Here is an example of a public class:
public class Person
{
public string name;
public int age;
public Person()
{
name = "Unknown";
age = 0;
}
Exercises:
1. Write a program that creates a Circle class with properties for radius and diameter. The
program should create an instance of the Circle class and calculate and print out the
circumference and area of the circle.
2. Write a program that creates a Book class with properties for title and author. The
program should create an array of Book objects and print out the title and author of
each book, sorted by author's last name in ascending order.
3. Write a program that creates a Movie class with properties for title, director, and
release year. The program should create an array of Movie objects and print out the
title, director, and release year of each movie, sorted by release year in descending
order.
4. Write a program that creates a Triangle class with properties for base and height. The
program should create an instance of the Triangle class and calculate and print out the
area of the triangle.
5. Write a program that creates a Time class with properties for hours, minutes, and
seconds. The program should create an instance of the Time class and print out the time
in 24-hour format, as well as the time in 12-hour format.