0
Guys i understand objects in real life
But i never really understood objects in programming. Can someone explain to me as if i m a kid. Thank you.
1 Antwort
+ 3
Do not complicate yourself too much, you can see the objects in programming in the same way that you see them in real life, a door for example, has height, width, color, which would be the attributes of that door, which in programming would be:
class Door
{
// attributes
int width;
int heigth;
Color color;
// constructor
public Door (int _width, int _heigth, Color _color)
{
width = _width;
heigth = _heigth;
color = _color;
}
}
This way you would have a class that would work like a blueprint for a door.
Door myDoor = new Door (50, 100, new Color (0,0,0));
In this way "myDoor" is an object of type "Door" to which we can access its attributes either to read them or to modify them, for example:
int doorWidth = myDoor.width;
// get the width of "myDoor", which is currently 50 and store it in doorWidth
myDoor.width = 100;
// set the width of "myDoor" that changes from 50 to 100, imagine that suddenly the door of your room becomes wider
myDoor.color = new Color (255,0,0);
// change the color of "myDoor" from black to red
You can also add methods to your objects, for example
class Door
{
// attributes
int width;
int heigth;
Color color;
// constructor
public Door (int _width, int _heigth, Color _color)
{
width = _width;
heigth = _heigth;
color = _color;
}
public void InvertDimensions ()
{
int tempWidth = width;
width = heigth;
heigth = tempWidth;
}
}
myDoor.width = 50;
myDoor.heigth = 100;
myDoor.InvertDimensions();
InvertDimensions() inverts the values of the width and height attributes, so now the width would be 100 and the height 50
Now imagine you need 3 doors, you can use the same "Door" class to create them, for example:
Door myDoor1 = new Door (50, 100, new Color (0,0,0));
Door myDoor2 = new Door (80, 150, new Color (0,255,0));
Door myDoor3 = new Door