oop-examples/lessons/Instances.md
2020-05-04 19:36:23 +02:00

2.1 KiB

Object Instances

For this short Introduction we'll only create two objects, give them some data and let them do their magic with one function.

Objects are generally used to keep data logically grouped and also make it easy to perform actions on them without having to account for all the logic at the time of using those functions.

As an example I have created a Car class. This is probably going to be the main class used in all further lessons, since it has a lot of room for more data and functions to add except for manufacturer, model and the function print_info in this example.

/*
 * First we create a new car and store that in a variable, here called 'a'.
 * Usually a programming language has a keyword like 'new' to instantiate new objects.
 * here in Java a new Object is created by Specifying variable type, variable name
 * the keyword new and again the type that should be instantiated.
 */
Car a = new Car();

/*
 * To access data within an object you can use the object name followed by a dot
 * and the name of the property.
 * The data can be read or modified at will.
 * Since this is just the start of working with oop,
 * I'll also use very early cars here
 */
a.manufacturer = "Benz";
a.model = "Velo";

/*
 * Then we do the same thing for a second car
 */
Car b = new Car();
b.manufacturer = "Ford";
b.model = "Model T";

/*
 * Functions can be accessed in the same way as properties, just with
 * parentheses behind to actually run the functions.
 * These will print out all the data we put into the objects before.
 */
a.print_info();
b.print_info();

The above example code together with the car class will create the following output:

Car Information:
- manufacturer: Benz
- model: Velo
Car Information:
- manufacturer: Ford
- model: Model T

If any of the examples don't produce the same output, then congrats, you just got yourself the homework to fix the error and submit a pull request to this repository :)

Examples