Classes and Objects (Lesson-25)

In this lesson, we will learn how to create a new class in our java project and create objects from the class. This is the basis of Object Oriented Programming (OOP).

Creating a new class in Netbeans Java project:
1. Right click the main package in your project.

2. Select New>>Java Class

3. In the next dialog, type the class name and click "Finish"

4. New class has been created. You can check it in your project.


We will be learning about attributes of a class in the next lesson. For now let's add a method to our new class. This time, the method will not be static. We will not be using the static keyword while declaring the method. Let's add a sayHello method which will display Hello on the screen.

You can switch between classes using the top tabs. If a class is not open in the IDE, you can open it by double clicking it from the left pane (in your project)

Now let's create an object of our class in the main method. To create an object of our class, we use the new keyword. It goes like this:

ClassName objectName = new ClassName();

Let's see how it looks in code:

To call a method from the newly created object, you use the object name and method name separated by period(.)

objectName.method();

Now let's call the sayHello method on our new object:

Let's have a review of what we did: We created a new class and defined a non-static sayHello method in it. Then we created the object of that class and called the sayHello method on the object.

*An object of a particular class is also called the instance of that class. The word instance means "copy". The object has all the things from the class and is thus a copy of the class. Like we defined the sayHello , method in our class and then we called the method from the object of that class. It means that the object of that class had a copy of all the methods in the class.

**We can create any number of objects (instances) from a class. It means that "write the code once and use it many times". This is the fundamental concept of Object Oriented Programming (OOP). In this way, OOP enables us to solve complex problems very easily.

Static vs non-static methods:
Static methods can be called without creating an object of the class but for non-static methods, the object of the class must be created. Now let's create a class that has both static and non static methods.

Now let's create object and call these methods from the main class.

So we should think that if static methods can be used in all conditions, why even we use the non static methods? Well.. the answer lies in the next lesson.

Post a Comment

0 Comments