Introduction to Object Oriented Programming in Java (Object and Classes)
Introduction👋🏻
Object Oriented Programming is a powerful programming principle that revolves around the concept of "objects". It provides a structured way to design, organize, and maintain code by modelling real-world entities as objects, each with its own properties and behaviours. OOP promotes modularity, reusability, and easier maintenance of code, making it a fundamental concept in modern software development.
You will be learning the concepts of OOP through these blogs series, so make sure to follow, this is going to be the first blog of the Object Oriented Programming series where you will learn about "Classes" and "Objects", in this course we will be using Java, but if you don't know Java then you have to make some efforts and try to implement your learnings in your favourite programming language yourself.
Prerequisites👨🏻💻
Understanding of Java
Basic programming
Let's begin.....!😃
What is a Class?
Class can be understood as a collection of named groups of properties and functions. It serves as a blueprint or template for the structure of an object. Yes I know it went way too technical but don't worry you will easily understand each and everything once I will provide you with a real-world analogy.
Now you may have a question that ok, I understood that class is a template sort of thing using which we create objects. But what is an object? Here is your answer.
What is an Object?
Object is a logical construct or instance of the class, it is the real physical thing that actually exists in the memory. Classes are just like templates like a blueprint of a house that does not exist in the real world but just on paper and following this blueprint we build a real house that is analogous to an object in programming.
Therefore, Classes don't exist physically as in memory and objects are real-world entities that exist physically or exist in the memory of the computer.
Real-world examples of Classes and Objects
Cars -
We know that the basic structure of the car (template) is already defined i.e. it should have an outer body, two headlamps, two backlights, steering, four tires, seats, type of engine etc. This is what we call a Class, a collection of groups of properties that will define the structure of an object which is a car in this case.
Now we will use this class to instantiate objects, which means we can create different types of cars by following the rules defined by the CAR CLASS.
You can understand from the diagram above that we have a class named CAR and it has certain properties namely type of engine, seats, and colour. Using these properties different manufacturers make their own objects or cars which have the same properties as defined by the class CAR but their characteristics may be the same or different.
Humans -
We can also think of humans as a class that has certain properties like two eyes, two legs, two hands, a mouth, two ears, a nose etc. and we persons are objects of the class human, someone may have small eyes their colour may be different, someone may have a big nose, someone may be shorter and someone maybe taller.
I hope you understood the concept of classes and objects with the help of diagrams, analogies and examples provided above. Now it's time to move to code and learn how it is implemented in Java.
Class and Object in Java
A class name in Java starts with a capital letter. Imagine someone telling you to store the name, age and country of origin of five people, how will you do that? You'll say I will create three arrays of length five and store the respective data in the respective arrays but what if he tells you to store it in a single variable? This is where the use of Classes comes to play.
Therefore you can also say that classes are used to create certain datatypes which can store values of different data types under the same variable.
How to define a class?
class MyClass() {
String name;
int age;
String country;
}
Now using this class we can create multiple person objects which can have the same or different names, ages and countries. While writing code you must have used the keyword 'new', like when creating an array you do something like int[] arr = new int[size]
.
The new keyword
Remember we discussed earlier in the blog that classes don't actually occupy any space in the memory but the objects do. The new keyword is the one responsible for the allocation of memory to the objects.
Thus, the new keyword is used to dynamically allocate memory to the object of a class when it is being created.
Dynamic allocation of memory means that the memory to the objects is allocated during the runtime.
Whenever you create any non-primitive data type you use the new keyword because they are the objects of some already defined class by the Java people and in order to use them we need to create their objects because classes don't exist physically. For example, ArrayList, as you can see 'ArrayList' starts with a capital letter hence it is a class, the name that you give to your list is your reference variable which will point to an object and the new keyword allocates the memory to it and the ArrayList<>()
is known as a Constructor. We will talk about constructors later on in this blog.
How to create an object
As discussed earlier, classes can be treated as a special type of datatype that can store values of different data types, hence in order to use it we have to create an object of it.
class MyClass() {
String name;
int age;
String country;
}
MyClass person_1 = new MyClass();
In the above example, MyClass is the class name specifying which class we want to use, person_1 is the name of the reference variable pointing to the object, new keyword will be used to allocate memory to this object during runtime and MyClass() is the constructor.
Types of variables
Reference variable: The name of the variable that you create during the object creation of a class is known as the reference variable. The reference variables are stored in the stack memory and the object they are pointing to is stored in the heap memory.
Class variables: The variables that you declare during defining a class are called class variables.
Instance variables: As the name suggests, instance means objects, the variables which are local to the object and are used to define them are called instance variables. For example, in the car example above different objects like BMW, Audi etc. had properties like colour, type of engine etc. these are called instance variables.
The dot operator
The dot operator links the instance variables to the object name, if you have ever used Javascript then you must have done something like item.name while extracting data from a JSON file.
Similarly, here the dot operator links the object and the instance variables together so that you can change, retrieve or manipulate the data stored in the object.
class MyClass() {
String name;
int age;
String country;
}
MyClass person_1 = new MyClass();
person_1.name = "Sreejit";
person_1.age = 21;
person_1. country = "India";
In the above example, we are now assigning values to the instance variables of the object that we created before. Similarly, you can create multiple other objects and assign them different or the same values. But won't it be a hectic task? Here is where Constructors come into the picture.
Constructors
Constructors decide what should happen when an object is being created. Constructors are defined inside the class. It is like a function that may or may not take parameters. Its primary purpose is to initialize the object's attributes or properties and set up the initial state of the object. Constructors ensure that an object is properly initialized and ready for use as soon as it is instantiated from a class. The constructor has no name and only has a return type that is the same as the class name.
class MyClass() {
String name;
int age;
String country;
MyClass() {
name = "Default",
age = 0;
country = "India";
}
}
MyClass person_1 = new MyClass();
System.out.println(name + " " + age + " " + country);
Can you guess what will be printed? Yes, you guessed it right. "Default" 0 "India"
will be printed because if we do not define the properties or value of our object on our own then the constructor will provide the instance variables with the default values that are defined inside the constructor.
Constructors can also accept arguments. You can pass the values to the instance variables of the object by passing the as an argument in the Constructor.
class MyClass() {
String name;
int age;
String country;
MyClass(name, age, country) {
this.name = name,
this.age = age;
this.country = country;
}
}
MyClass person_1 = new MyClass("Yash", 20, "India");
System.out.println(person_1.name + " " + person_1.age + " " + person_1.country);
MyClass person_2 = new MyClass("David", 31, "USA");
System.out.println(person_2.name + " " + person_2.age + " " + person_2.country);
Yes, I know your question. What is 'this'?
This keyword
This keyword is nothing it just replaces itself with the name of the reference variable. This means, in the code above when the object of person_1 will be created then the 'this' will be replaced by 'person_1'. If you change the variable name in the parameter of the constructor then you can omit the this keyword but as a convention, it should be used whenever you are defining a function. In fact, it should also be used in constructors without parameters as well.
In other words the this keyword reference the current object with its instance variables.
How do things work internally?
When you define an object for a class then Java first checks whether you have defined or passed any values for the instance variables or not, if not it sets the values of the instance variable to the default values defined in the default constructor (The constructor with no parameters). If you have not defined the default constructor then it will set the value of the instance variables to the default value of its data type like int will have a default value of 0.
Now, if you have passed the values of the instance variables as arguments to the constructor then inside the constructor the this keyword is replaced by the name of the reference variable for which the object is being created.
class MyClass() {
String name;
int age;
String country;
// Default constructor
MyClass() {
this.name = "Default";
this.age = 0;
this.country = "India";
}
MyClass(name, age, country) {
this.name = name,
this.age = age;
this.country = country;
}
}
MyClass person_1 = new MyClass("Yash", 20, "India");
System.out.println(person_1.name + " " + person_1.age + " " + person_1.country);
MyClass person_2 = new MyClass();
System.out.println(person_2.name + " " + person_2.age + " " + person_2.country);
When two constructors have the same name then it is known as Constructor Overloading, the same as function overloading. In the above example, person_1 is an instance of the class MyClass and has instance variables that have some values, whereas person_2 is an instance of the class which has default values set to its instance variables.
Pack up!
That was it in the Objects and Classes blog of the OOP series, I hope you were able to understand the concepts and examples of this blog. Go try implementing what you have learnt today.
In the next blog, we will be learning about packages and the static keyword. I hope you enjoyed reading the blog, make sure to like the blog and follow me here on Hashnode.
I am also active on Twitter, you can follow me there as well. Ok, Goodbye! Happy Coding.