10. Core Java for complete beginners.
Objects and classes in Java.
Objects and classes in Java.
So far, we’ve discussed basics of Java, and now it’s the time to dive into core Java concepts. A fundamental rule that we all know is that Java is an object-oriented programming language. As a first-time learner, you might wonder what “Object-Oriented Programming” means. Don’t worry, we’ll learn all these concepts one by one.
At this stage, the first concept we need to explore is the Object. Think about the real world before diving into programming. What are objects in the real world? Everything around you is an object, right? Your laptop, keyboard, mouse, car, etc. Therefor, you can consider everything around you as an object.
Objects have two things: they know something and they do something.
Imagine a pen. The pen knows something, meaning it has its own physical properties like color, height, and weight. On the other hand, the pen does something, like writing. When the object does something, we call it as behaviors.
Therefor keep in mind objects have properties and behaviors.
Now with that understanding, let’s move into the programming world. In programming, everything is also an object. Even humans are treated as objects in programming. When you build an application in Java, you need to create different objects for it. So from now on in your Java journey, treat everything as an object.
For example, if you need to add two numbers together, the first thing that should come to your mind is, I need to create an object that can add those two numbers together.
Now I believe you have a basic idea about objects.
However, in Java, to create an object, you need a class first. Therefore, before you create an object, you need to create a class.
Now will see the link between an objects and classes further with a question, ” Who creates objects in Java? ”. But before we find the answer for that question, will find the answer for “ who creates objects in the real world? ”.
Imagine that you need to create a physical table and you’re an English speaker who doesn’t understand Chinese. Also imagine that you go to China to create that Table. Then you need to speak with a local carpenter who only knows Chinese to create the table. Then definitely you’d need a translator to communicate with the local Chinese carpenter. After that you would sketch or discuss the design of the table with your translator, who then communicates with the Chinese carpenter to get the table made.
Similarly, in object creation in Java, as a programmer, you need to design the class file, which is the blueprint of the object. Then the class file gets compiled into byte code, and the JVM uses this byte code to create the object.
So, ”who creates the object?”. The JVM creates objects.
Therefor, If you ask the JVM to create an object, JVM will say, “Okay, sure, it’s my job to create objects, but to create an object, give me the blueprint, which is the class file.”
Therefore, you can say that the class file is the blueprint of an object and every object has properties and methods.
Here is a simple example (Code-01) to get the addition of num1
and num2
variables. Check this out.
Code-01:
public class Main {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
int result = num1 + num2;
System.out.println("The result: " + result);
}
}
This code will output 9
.
The above example (Code-01) is one way of get the addition of num1
and num2
variables. Now my goal is to get the addition of the same num1
and num2
variables and print the result using objects and classes in Java. Let's do the same task differently with objects and classes.
In Java whatever you do, you need to do inside a class. Inside a class you would create methods, variables etc.
Then the next question is, where do we create classes, you can create a class in the same Java file and below I did the same
Look at the following example (Code-02), where we aim to add num1
and num2
.
Code-02:
class Calculator {
public int add() {
System.out.println("Dinesh");
return 5; // Just an example, since the return type is int.
}
}
public class Main {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
}
}
Like I explained you before, to add these two numbers, you need an object. Therefor first thing you need to do is, creating a class because the class is the blueprint of the object.
In other words, as our goal is to add two numbers together, to accomplish this, we need an object. Before creating an object, we need a class, which serves as the blueprint for objects. Using the Calculator class, I designed the object, and the JVM will handle the creation of this object.
In the code above, I have used several keywords to create a method, but those keywords will be discussed in detail in upcoming articles.
When I create the add
method in the Calculator
class, I use public
and int
. Public
means I can access this method from outside the class, and int
indicates the return type of the add
method. When the add
method is called, it performs operations and returns an integer value. In the code above, I have written "Dinesh" and return 5;
.
Note: In the above example, I return the number 5 to show how the code works. Other than that returning 5 does not have any purpose in the above code.
So far, I have created the Calculator
class separately from the main method. But now, the problem is, if you run the above code, will it work? No, it won't. The reason is that I haven't called the add
method yet.
Here’s a golden rule: always remember that the JVM enters your program from the main class.
Therefore, in the above code, the JVM will enter into the code from the main class and will start to execute the code. The problem is the code will execute but it will not print anything.
To fix this problem, you need to write code to call the add
method inside the main method. Let's fine-tune the above code further.
Check the below code. I have just put add();
. Remember, in some other programming languages, this works, but in Java, just calling the method itself will give you the following error.
Code-03:
class Calculator {
public int add() {
System.out.println("Dinesh");
return 5;
}
}
public class Main {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
add(); // This will cause an error.
}
}
The error:
java: cannot find symbol
symbol: method add()
location: class Main
The error indicates that the add
method cannot be found in the Main
class. The problem is that the object is missing. To fix this, create an object of the Calculator
class.
Code-04:
Calculator cal = new Calculator();
Take look at the explanation of the code-04.
Left Side of the Code:
“The left side of the code, Calculator cal
, says 'I have a class called Calculator
, and I want to create a variable named cal
that will hold an object of type Calculator
.' Therefore, we can say that cal
is a variable, and its type is Calculator
."
Right Side of the Code:
“The right side of the code, new Calculator()
, says 'Create a new instance of the Calculator
class.' The new
keyword is used to allocate memory for this new object, and Calculator()
is the constructor call which initializes the new object."
Putting It All Together:
“So, when you write Calculator cal = new Calculator();
, you're saying 'I have a Calculator
class, and I want to create a variable named cal
of this type. Then, I want to create a new Calculator
object and assign it to cal
.' This means cal
will now hold a reference to this newly created Calculator
object."
Now the question is, how does the
cal
variable differ fromint num = 4;
? Remember,num
is a primitive variable, andcal
is a reference variable.
This is how you create the object. Java has a concept called a constructor, which we'll learn about in the future. For now, this is how we create an object.
Therefor now the object is created and to call the add
method, use the following code indie the main method.
Code-05:
cal.add();
With all improvements, below is the final code, which will print “Dinesh” as the output. When you run the code the add
method is getting called.
Code-06:
class Calculator {
public int add() {
System.out.println("Dinesh");
return 5;
}
}
public class Main {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
Calculator cal = new Calculator();
cal.add();
}
}
Code-06 allows us to call the add
method from the Calculator
class from the main
method. However, there's still an issue. Although the add
method returns a value of 5, when I run the code, it only prints 'Dinesh'.
To fix this, I improved the code as follows.
The add
method returns the value 5 to the main
method. Then what you need to think is, who receives the value returned from the add
method?
To fix this problem I created a result
variable and assigned it to cal.add();.
int result = cal.add();
The complete code below prints both “Dinesh” and “5”.
Code-07:
class Calculator {
public int add() {
System.out.println("Dinesh");
return 5;
}
}
public class Main {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
Calculator cal = new Calculator();
int result = cal.add();
System.out.println(result);
}
}
Now you know how to create a class, create an object, and call a method from another method. However, if you check Code-07, you’ll notice that I haven’t yet used the num1
and num2
variables created in the main class. Our goal in this blog post is to add two numbers using an object and class. Therefore, take a look at the exercise below where I combine everything to get the sum of two numbers using an object and class.
Let’s solve a problem, Imagine you’re given two numbers, and you need to get their sum using another method.
// Define the Calculator class
class Calculator {
// Define the add method which takes two integers as parameters and returns their sum
public int add(int n1, int n2) {
int r = n1 + n2;
return r; // Return the calculated sum
}
}
// Define the Main class which contains the main method, the entry point of the program
public class Main {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
Calculator cal = new Calculator(); // Create an instance of the Calculator class
// Call the add method on the cal object, passing num1 and num2 as arguments
// The return value of the add method is assigned to the variable result
int result = cal.add(num1, num2); // num1 and num2 values will be passed to add method.
System.out.println("The final result: " + result);
}
}
The code will below result.
The final result:9