Introduction to classes with real-world Examples
10. Real world examples of classes, methods and Objects in Comparision with Object Oriented Programming
A class is like a blueprint for creating similar objects.
Let's take a real-world example
A car company has a blueprint of any car model and based on that they create similar kind of cars.
Here, every car is an object and the blueprint of car is like a class.
every car object has it's own attributes such as weight, color, seating capacity, etc. and methods such as driving, applying breaks, turning on headlights, etc.
A class defines a new data type. Once defined, this new type can be used to create objects of that type. Means a class is a template for an object, and an object is an instance of an class. In other terms an Object is a specific case of a class.
The General form of a class
Syntax:
class name { type instance-variable1; type instance-variable2; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } }
- A class is declared by using the keyword
class
. - The variables defined within a class are called instance variables.
- The methods and variables defined inside a class are called member of that class.
- Variables defined within a class are called instance variables because each object of the class contains its own copy of these variables. That means, the data for one object is unique from the data for another.
A simple Class
class Box { double width; double height; double depth; }
In above example the new data type is called Box. Now, Box can be used to declare objects of type Box.
A class declaration only creates a template; it does not create an actual object.
To create an actual object of type box we have to use statement like the one below
// create a Box object called mybox Box mybox = new Box();
Now, a new box object is created thus, it will contain its own copies of the
instance variables width, height, and depth. To access this variables you will
use the dot(.
) operator.
mybox.width = 100;
Here is the complete code of the program that uses a box class
Real-world Examples of classes their data and methods
Also checkout some of the interesting notes you may like.
Comments