class Person
{
private int age;
private string name;
private double weight;
private double height;
public int GetAge()
{
return age;
}
public void SetAge(int newAge)
{
age = newAge;
}
public string GetName()
{
return name;
}
public void SetName(string newName)
{
name = newName;
}
public double GetWeight()
{
return weight;
}
public void SetWeight(double newWeight)
{
weight = newWeight;
}
public double GetHeight()
{
return height;
}
public void SetHeight(double newHeight)
{
height = newHeight;
}
}
class Program
{
static void Main(string[] args)
{
Person David = new Person();
Person Alice = new Person();
// Initialize David
David.SetAge(21);
David.SetName("David");
David.SetWeight(185.4);
David.SetHeight(72.3);
// Initialize Alice
Alice.SetAge(18);
Alice.SetName("Alice");
Alice.SetWeight(125.7);
Alice.SetHeight(67.1);
// Print all instance variables of David
Console.WriteLine("David: age = {0}, name = {1}, weight = {2}, height = {3}", David.GetAge(), David.GetName(), David.GetWeight(), David.GetHeight());
// Print all instance variables of Alice
Console.WriteLine("Alice: age = {0}, name = {1}, weight = {2}, height = {3}", Alice.GetAge(), Alice.GetName(), Alice.GetWeight(), Alice.GetHeight());
}
}
In the modified code, the attributes (age, name, weight, height) of the Person class are defined as private. We have added public methods (getters and setters) to access and modify these attributes. By encapsulating the attributes, we achieve data hiding and provide controlled access to them.
The getters (e.g., GetAge, GetName, etc.) are used to retrieve the values of the private attributes, and the setters (e.g., SetAge, SetName, etc.) are used to set new values for the attributes.
In the Main method, we now use the setters to initialize the attributes for David and Alice. When printing the values, we use the getters to retrieve the attribute values.
Encapsulation is a fundamental concept in object-oriented programming that promotes data integrity and helps maintain code flexibility and reusability. By encapsulating the attributes, we can control access to them and enforce data validation or business logic if needed.