What are “Classes” in programming and how are they distinct from functions? What about their applications?

281 views

What are “Classes” in programming and how are they distinct from functions? What about their applications?

In: 10

21 Answers

Anonymous 0 Comments

They’re not too hard to grasp. Think of a class like a container for all the relevant bits of an object, like the things it can do and any data.

The class ‘Car’, for example, might have;
`int numberOfWheels, float fuelInTankLitres, string registrationNo;`
It might also contain some functions that are required for the car’s function;
`StartEngine(); EnableAC(); LockDoors();`
If we create an object from this called firstCar, we can use `firstCar.registrationNo = 7JML581;` to register that car.

We could say;
`Car firstCar = new Car;`
`firstCar.fuelInTank = 10f;`
`if (firstCar.fuelInTank > 0) then firstCar.StartEngine();`
This uses the Car class to create a new object, the firstCar, and lets you access that object, specifically, without affecting the template. Using the same code, after that part, we could write;
`Car secondCar = new Car;`
`secondCar.LockDoors();`
`secondCar.EnableAC();`
The first car starts its engine, the second car locks its doors and its heating turns on, but the second car doesn’t start. While the template is the same, the two cars are different and separate entities of their own.